From 01b0efc4be6b8963eeff0fcd0c5a35f3edeb5545 Mon Sep 17 00:00:00 2001 From: Fan Shang Xiang Date: Mon, 27 Nov 2023 14:45:40 +0800 Subject: [PATCH] refactor: load config with configloader Signed-off-by: Fan Shang Xiang --- go.mod | 44 +- go.sum | 82 +- pkg/azureutils/azure_disk_utils.go | 37 +- .../armcontainerregistry/CHANGELOG.md | 315 + .../armcontainerregistry/LICENSE.txt | 21 + .../armcontainerregistry/README.md | 99 + .../armcontainerregistry/agentpools_client.go | 495 ++ .../armcontainerregistry/assets.json | 6 + .../armcontainerregistry/autorest.md | 13 + .../armcontainerregistry/build.go | 7 + .../armcontainerregistry/cacherules_client.go | 428 + .../armcontainerregistry/ci.yml | 28 + .../armcontainerregistry/client_factory.go | 116 + .../armcontainerregistry/constants.go | 760 ++ .../credentialsets_client.go | 431 ++ .../armcontainerregistry/interfaces.go | 36 + .../armcontainerregistry/models.go | 2495 ++++++ .../armcontainerregistry/models_serde.go | 6147 +++++++++++++++ .../armcontainerregistry/operations_client.go | 88 + .../armcontainerregistry/options.go | 447 ++ .../polymorphic_helpers.go | 88 + .../privateendpointconnections_client.go | 346 + .../armcontainerregistry/registries_client.go | 1156 +++ .../replications_client.go | 430 ++ .../armcontainerregistry/response_types.go | 469 ++ .../armcontainerregistry/runs_client.go | 417 + .../armcontainerregistry/scopemaps_client.go | 428 + .../armcontainerregistry/taskruns_client.go | 494 ++ .../armcontainerregistry/tasks_client.go | 494 ++ .../armcontainerregistry/time_rfc3339.go | 86 + .../armcontainerregistry/tokens_client.go | 428 + .../armcontainerregistry/webhooks_client.go | 635 ++ .../armcontainerservice/v4/CHANGELOG.md | 147 + .../v4/agentpools_client.go | 40 +- .../armcontainerservice/v4/assets.json | 2 +- .../armcontainerservice/v4/autorest.md | 8 +- .../armcontainerservice/v4/constants.go | 38 +- .../v4/maintenanceconfigurations_client.go | 16 +- .../v4/managedclusters_client.go | 378 +- .../armcontainerservice/v4/models.go | 177 + .../armcontainerservice/v4/models_serde.go | 513 ++ .../v4/operations_client.go | 4 +- .../armcontainerservice/v4/options.go | 24 + .../v4/privateendpointconnections_client.go | 18 +- .../v4/privatelinkresources_client.go | 4 +- .../v4/resolveprivatelinkserviceid_client.go | 4 +- .../armcontainerservice/v4/response_types.go | 24 + .../v4/snapshots_client.go | 24 +- .../keyvault/armkeyvault/CHANGELOG.md | 77 + .../keyvault/armkeyvault/LICENSE.txt | 21 + .../keyvault/armkeyvault/README.md | 91 + .../keyvault/armkeyvault/assets.json | 6 + .../keyvault/armkeyvault/autorest.md | 15 + .../keyvault/armkeyvault/build.go | 7 + .../keyvault/armkeyvault/ci.yml | 28 + .../keyvault/armkeyvault/client_factory.go | 94 + .../keyvault/armkeyvault/constants.go | 647 ++ .../keyvault/armkeyvault/keys_client.go | 396 + .../armkeyvault/managedhsmkeys_client.go | 405 + .../armkeyvault/managedhsms_client.go | 691 ++ .../mhsmprivateendpointconnections_client.go | 337 + .../mhsmprivatelinkresources_client.go | 106 + .../armkeyvault/mhsmregions_client.go | 115 + .../keyvault/armkeyvault/models.go | 1402 ++++ .../keyvault/armkeyvault/models_serde.go | 3636 +++++++++ .../keyvault/armkeyvault/operations_client.go | 93 + .../keyvault/armkeyvault/options.go | 283 + .../privateendpointconnections_client.go | 337 + .../privatelinkresources_client.go | 106 + .../keyvault/armkeyvault/response_types.go | 305 + .../keyvault/armkeyvault/secrets_client.go | 328 + .../keyvault/armkeyvault/time_rfc3339.go | 86 + .../keyvault/armkeyvault/time_unix.go | 61 + .../keyvault/armkeyvault/vaults_client.go | 799 ++ .../storage/armstorage/CHANGELOG.md | 68 + .../storage/armstorage/LICENSE.txt | 21 + .../storage/armstorage/README.md | 102 + .../storage/armstorage/accounts_client.go | 1330 ++++ .../storage/armstorage/assets.json | 6 + .../storage/armstorage/autorest.md | 15 + .../armstorage/blobcontainers_client.go | 1151 +++ .../blobinventorypolicies_client.go | 318 + .../storage/armstorage/blobservices_client.go | 251 + .../storage/armstorage/build.go | 7 + .../resourcemanager/storage/armstorage/ci.yml | 28 + .../storage/armstorage/client_factory.go | 158 + .../storage/armstorage/constants.go | 1274 +++ .../armstorage/deletedaccounts_client.go | 163 + .../armstorage/encryptionscopes_client.go | 347 + .../storage/armstorage/fileservices_client.go | 249 + .../storage/armstorage/fileshares_client.go | 572 ++ .../storage/armstorage/localusers_client.go | 461 ++ .../armstorage/managementpolicies_client.go | 249 + .../storage/armstorage/models.go | 2832 +++++++ .../storage/armstorage/models_serde.go | 6851 +++++++++++++++++ .../objectreplicationpolicies_client.go | 324 + .../storage/armstorage/operations_client.go | 89 + .../storage/armstorage/options.go | 577 ++ .../privateendpointconnections_client.go | 318 + .../armstorage/privatelinkresources_client.go | 110 + .../storage/armstorage/queue_client.go | 401 + .../armstorage/queueservices_client.go | 250 + .../storage/armstorage/response_types.go | 557 ++ .../storage/armstorage/skus_client.go | 99 + .../storage/armstorage/table_client.go | 395 + .../armstorage/tableservices_client.go | 250 + .../storage/armstorage/time_rfc3339.go | 86 + .../storage/armstorage/usages_client.go | 105 + .../github.com/evanphx/json-patch/README.md | 4 +- vendor/github.com/evanphx/json-patch/patch.go | 46 +- .../github.com/felixge/httpsnoop/.travis.yml | 6 - vendor/github.com/felixge/httpsnoop/Makefile | 2 +- vendor/github.com/felixge/httpsnoop/README.md | 4 +- .../felixge/httpsnoop/capture_metrics.go | 2 +- .../httpsnoop/wrap_generated_gteq_1.8.go | 2 +- .../httpsnoop/wrap_generated_lt_1.8.go | 2 +- .../github.com/fsnotify/fsnotify/.cirrus.yml | 13 + .../github.com/fsnotify/fsnotify/.gitignore | 1 + .../github.com/fsnotify/fsnotify/CHANGELOG.md | 83 +- vendor/github.com/fsnotify/fsnotify/README.md | 81 +- .../fsnotify/fsnotify/backend_fen.go | 552 +- .../fsnotify/fsnotify/backend_inotify.go | 377 +- .../fsnotify/fsnotify/backend_kqueue.go | 295 +- .../fsnotify/fsnotify/backend_other.go | 205 +- .../fsnotify/fsnotify/backend_windows.go | 247 +- .../github.com/fsnotify/fsnotify/fsnotify.go | 91 +- vendor/github.com/fsnotify/fsnotify/mkdoc.zsh | 125 +- vendor/github.com/google/uuid/CHANGELOG.md | 11 + vendor/github.com/google/uuid/CONTRIBUTING.md | 2 +- vendor/github.com/google/uuid/uuid.go | 26 +- vendor/github.com/onsi/ginkgo/v2/CHANGELOG.md | 12 + .../ginkgo/v2/ginkgo/internal/test_suite.go | 3 +- .../onsi/ginkgo/v2/types/version.go | 2 +- vendor/github.com/onsi/gomega/CHANGELOG.md | 23 + vendor/github.com/onsi/gomega/gomega_dsl.go | 10 +- vendor/github.com/onsi/gomega/matchers.go | 56 +- .../onsi/gomega/matchers/be_false_matcher.go | 13 +- .../onsi/gomega/matchers/be_true_matcher.go | 13 +- .../gomega/matchers/match_error_matcher.go | 25 +- vendor/github.com/spf13/cobra/.golangci.yml | 8 +- vendor/github.com/spf13/cobra/README.md | 8 +- vendor/github.com/spf13/cobra/active_help.go | 10 +- vendor/github.com/spf13/cobra/active_help.md | 157 - .../spf13/cobra/bash_completions.go | 2 +- .../spf13/cobra/bash_completions.md | 93 - .../spf13/cobra/bash_completionsV2.go | 2 +- vendor/github.com/spf13/cobra/cobra.go | 13 +- vendor/github.com/spf13/cobra/command.go | 69 +- vendor/github.com/spf13/cobra/completions.go | 29 +- .../spf13/cobra/fish_completions.go | 2 +- .../spf13/cobra/fish_completions.md | 4 - vendor/github.com/spf13/cobra/flag_groups.go | 68 +- .../spf13/cobra/powershell_completions.go | 6 +- .../spf13/cobra/powershell_completions.md | 3 - .../spf13/cobra/projects_using_cobra.md | 64 - .../spf13/cobra/shell_completions.md | 576 -- vendor/github.com/spf13/cobra/user_guide.md | 726 -- .../github.com/spf13/cobra/zsh_completions.md | 48 - .../net/http/otelhttp/common.go | 4 +- .../net/http/otelhttp/config.go | 7 +- .../net/http/otelhttp/handler.go | 18 +- .../net/http/otelhttp/version.go | 2 +- .../x/crypto/chacha20/chacha_arm64.go | 1 - .../x/crypto/chacha20/chacha_arm64.s | 1 - .../x/crypto/chacha20/chacha_noasm.go | 1 - .../x/crypto/chacha20/chacha_ppc64le.go | 1 - .../x/crypto/chacha20/chacha_ppc64le.s | 1 - .../x/crypto/chacha20/chacha_s390x.go | 1 - .../x/crypto/chacha20/chacha_s390x.s | 1 - .../curve25519/internal/field/fe_amd64.go | 1 - .../curve25519/internal/field/fe_amd64.s | 1 - .../internal/field/fe_amd64_noasm.go | 1 - .../curve25519/internal/field/fe_arm64.go | 1 - .../curve25519/internal/field/fe_arm64.s | 1 - .../internal/field/fe_arm64_noasm.go | 1 - vendor/golang.org/x/crypto/hkdf/hkdf.go | 4 +- .../x/crypto/internal/alias/alias.go | 1 - .../x/crypto/internal/alias/alias_purego.go | 1 - .../x/crypto/internal/poly1305/bits_compat.go | 1 - .../x/crypto/internal/poly1305/bits_go1.13.go | 1 - .../x/crypto/internal/poly1305/mac_noasm.go | 1 - .../x/crypto/internal/poly1305/sum_amd64.go | 1 - .../x/crypto/internal/poly1305/sum_amd64.s | 1 - .../x/crypto/internal/poly1305/sum_ppc64le.go | 1 - .../x/crypto/internal/poly1305/sum_ppc64le.s | 1 - .../x/crypto/internal/poly1305/sum_s390x.go | 1 - .../x/crypto/internal/poly1305/sum_s390x.s | 1 - .../x/crypto/salsa20/salsa/salsa20_amd64.go | 1 - .../x/crypto/salsa20/salsa/salsa20_amd64.s | 1 - .../x/crypto/salsa20/salsa/salsa20_noasm.go | 1 - vendor/golang.org/x/crypto/ssh/common.go | 3 - vendor/golang.org/x/crypto/ssh/handshake.go | 7 + vendor/golang.org/x/crypto/ssh/keys.go | 19 +- vendor/golang.org/x/crypto/ssh/server.go | 20 +- vendor/golang.org/x/sync/errgroup/go120.go | 1 - .../golang.org/x/sync/errgroup/pre_go120.go | 1 - vendor/golang.org/x/term/term_unix.go | 1 - vendor/golang.org/x/term/term_unix_bsd.go | 1 - vendor/golang.org/x/term/term_unix_other.go | 1 - vendor/golang.org/x/term/term_unsupported.go | 1 - .../golang.org/x/text/message/catalog/go19.go | 1 - .../x/text/message/catalog/gopre19.go | 1 - .../x/text/secure/bidirule/bidirule10.0.0.go | 1 - .../x/text/secure/bidirule/bidirule9.0.0.go | 1 - .../x/text/unicode/bidi/tables10.0.0.go | 1 - .../x/text/unicode/bidi/tables11.0.0.go | 1 - .../x/text/unicode/bidi/tables12.0.0.go | 1 - .../x/text/unicode/bidi/tables13.0.0.go | 1 - .../x/text/unicode/bidi/tables15.0.0.go | 1 - .../x/text/unicode/bidi/tables9.0.0.go | 1 - .../x/text/unicode/norm/tables10.0.0.go | 1 - .../x/text/unicode/norm/tables11.0.0.go | 1 - .../x/text/unicode/norm/tables12.0.0.go | 1 - .../x/text/unicode/norm/tables13.0.0.go | 1 - .../x/text/unicode/norm/tables15.0.0.go | 1 - .../x/text/unicode/norm/tables9.0.0.go | 1 - .../golang.org/x/text/width/tables10.0.0.go | 1 - .../golang.org/x/text/width/tables11.0.0.go | 1 - .../golang.org/x/text/width/tables12.0.0.go | 1 - .../golang.org/x/text/width/tables13.0.0.go | 1 - .../golang.org/x/text/width/tables15.0.0.go | 1 - vendor/golang.org/x/text/width/tables9.0.0.go | 1 - .../x/tools/cmd/stringer/stringer.go | 5 +- .../tools/go/internal/packagesdriver/sizes.go | 11 +- vendor/golang.org/x/tools/go/packages/doc.go | 2 +- .../golang.org/x/tools/go/packages/golist.go | 16 +- .../x/tools/go/packages/packages.go | 11 +- .../x/tools/go/types/objectpath/objectpath.go | 21 +- .../x/tools/internal/gcimporter/gcimporter.go | 3 +- .../x/tools/internal/typeparams/coretype.go | 8 +- .../x/tools/internal/typeparams/termlist.go | 2 +- .../x/tools/internal/typeparams/typeterm.go | 9 +- .../internal/typesinternal/objectpath.go | 24 + .../x/tools/internal/typesinternal/types.go | 16 - .../k8s.io/cloud-provider/api/retry_error.go | 46 + .../api/well_known_annotations.go | 26 + .../cloud-provider/api/well_known_taints.go | 28 + .../cloud-provider/node/helpers/address.go | 146 + .../cloud-provider/node/helpers/labels.go | 103 + .../cloud-provider/node/helpers/taints.go | 245 + .../component-helpers/node/util/cidr.go | 58 + .../component-helpers/node/util/conditions.go | 57 + .../component-helpers/node/util/hostname.go | 46 + .../k8s.io/component-helpers/node/util/ips.go | 82 + .../component-helpers/node/util/status.go | 134 + vendor/modules.txt | 82 +- .../pkg/azclient/Makefile | 14 +- .../pkg/azclient/accountclient/custom.go | 62 + .../pkg/azclient/accountclient/interface.go | 35 + .../accountclient/zz_generated_client.go | 57 + .../azclient/blobcontainerclient/custom.go | 49 + .../azclient/blobcontainerclient/interface.go | 34 + .../zz_generated_client.go | 55 + .../blobservicepropertiesclient/custom.go | 42 + .../blobservicepropertiesclient/interface.go | 30 + .../zz_generated_client.go | 42 + .../pkg/azclient/configloader/LICENSE | 202 + .../azclient/configloader/config_loader.go | 25 + .../pkg/azclient/configloader/load.go | 82 + .../pkg/azclient/configloader/loader_empty.go | 38 + .../pkg/azclient/configloader/loader_file.go | 63 + .../azclient/configloader/loader_secret.go | 100 + .../pkg/azclient/configloader/loader_yaml.go | 54 + .../pkg/azclient/factory.go | 16 + .../pkg/azclient/factory_gen.go | 148 +- .../pkg/azclient/fileshareclient/custom.go | 45 + .../pkg/azclient/fileshareclient/interface.go | 34 + .../fileshareclient/zz_generated_client.go | 55 + .../pkg/azclient/interfaceclient/custom.go | 46 + .../pkg/azclient/interfaceclient/interface.go | 3 +- .../pkg/azclient/providerclient/custom.go | 62 + .../pkg/azclient/providerclient/interface.go | 31 + .../providerclient/zz_generated_client.go | 42 + .../pkg/azclient/registryclient/custom.go | 41 + .../pkg/azclient/registryclient/interface.go | 35 + .../registryclient/zz_generated_client.go | 74 + .../azclient/routetableclient/interface.go | 4 +- .../routetableclient/zz_generated_client.go | 24 + .../pkg/azclient/secretclient/custom.go | 32 + .../pkg/azclient/secretclient/interface.go | 33 + .../secretclient/zz_generated_client.go | 68 + .../pkg/azclient/vaultclient/custom.go | 48 + .../pkg/azclient/vaultclient/interface.go | 35 + .../vaultclient/zz_generated_client.go | 68 + .../virtualmachinescalesetclient/custom.go | 37 + .../virtualmachinescalesetclient/interface.go | 6 +- .../zz_generated_client.go | 11 - .../azclient/virtualnetworkclient/custom.go | 32 + .../virtualnetworkclient/interface.go | 3 + .../azure_deploymentclient.go | 2 +- .../vmssclient/azure_vmssclient.go | 6 +- .../pkg/azureclients/vmssclient/interface.go | 4 +- .../cloud-provider-azure/pkg/consts/consts.go | 29 +- .../pkg/consts/helpers.go | 7 +- .../pkg/provider/azure.go | 322 +- .../pkg/provider/azure_config.go | 61 - .../pkg/provider/azure_controller_standard.go | 2 +- .../pkg/provider/azure_controller_vmssflex.go | 2 +- .../pkg/provider/azure_fakes.go | 2 +- .../pkg/provider/azure_instances.go | 1 + .../pkg/provider/azure_loadbalancer.go | 196 +- .../azure_loadbalancer_backendpool.go | 58 +- .../azure_loadbalancer_healthprobe.go | 124 +- .../pkg/provider/azure_loadbalancer_repo.go | 9 + .../pkg/provider/azure_local_services.go | 114 +- .../provider/azure_managedDiskController.go | 32 +- .../azure_mock_loadbalancer_backendpool.go | 4 +- .../pkg/provider/azure_privatelinkservice.go | 46 +- .../provider/azure_privatelinkservice_repo.go | 41 +- .../pkg/provider/azure_publicip_repo.go | 6 +- .../pkg/provider/azure_routes.go | 4 + .../pkg/provider/azure_standard.go | 22 +- .../pkg/provider/azure_storageaccount.go | 31 +- .../pkg/provider/azure_utils.go | 19 +- .../pkg/provider/azure_vmss.go | 4 +- .../pkg/provider/azure_vmss_cache.go | 47 +- .../pkg/provider/azure_vmssflex.go | 33 +- .../pkg/provider/azure_wrap.go | 4 + .../provider/loadbalancer/accesscontrol.go | 202 + .../pkg/provider/loadbalancer/netip.go | 50 + .../pkg/util/taints/taints.go | 29 + vendor/sigs.k8s.io/yaml/LICENSE | 256 + vendor/sigs.k8s.io/yaml/OWNERS | 8 +- vendor/sigs.k8s.io/yaml/fields.go | 55 +- vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE | 201 + .../yaml/goyaml.v2/LICENSE.libyaml | 31 + vendor/sigs.k8s.io/yaml/goyaml.v2/NOTICE | 13 + vendor/sigs.k8s.io/yaml/goyaml.v2/OWNERS | 24 + vendor/sigs.k8s.io/yaml/goyaml.v2/README.md | 143 + vendor/sigs.k8s.io/yaml/goyaml.v2/apic.go | 744 ++ vendor/sigs.k8s.io/yaml/goyaml.v2/decode.go | 815 ++ vendor/sigs.k8s.io/yaml/goyaml.v2/emitterc.go | 1685 ++++ vendor/sigs.k8s.io/yaml/goyaml.v2/encode.go | 390 + vendor/sigs.k8s.io/yaml/goyaml.v2/parserc.go | 1095 +++ vendor/sigs.k8s.io/yaml/goyaml.v2/readerc.go | 412 + vendor/sigs.k8s.io/yaml/goyaml.v2/resolve.go | 258 + vendor/sigs.k8s.io/yaml/goyaml.v2/scannerc.go | 2711 +++++++ vendor/sigs.k8s.io/yaml/goyaml.v2/sorter.go | 113 + vendor/sigs.k8s.io/yaml/goyaml.v2/writerc.go | 26 + vendor/sigs.k8s.io/yaml/goyaml.v2/yaml.go | 478 ++ vendor/sigs.k8s.io/yaml/goyaml.v2/yamlh.go | 739 ++ .../yaml/goyaml.v2/yamlprivateh.go | 173 + vendor/sigs.k8s.io/yaml/yaml.go | 145 +- vendor/sigs.k8s.io/yaml/yaml_go110.go | 17 + 344 files changed, 65927 insertions(+), 3150 deletions(-) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/CHANGELOG.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/LICENSE.txt create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/README.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/agentpools_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/assets.json create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/autorest.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/build.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/cacherules_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/ci.yml create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/client_factory.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/constants.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/credentialsets_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/interfaces.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models_serde.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/operations_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/options.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/polymorphic_helpers.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/privateendpointconnections_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/registries_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/replications_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/response_types.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/runs_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/scopemaps_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/taskruns_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tasks_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/time_rfc3339.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tokens_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/webhooks_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/CHANGELOG.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/LICENSE.txt create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/README.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/assets.json create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/autorest.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/build.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/ci.yml create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/client_factory.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/constants.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/keys_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsmkeys_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsms_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivateendpointconnections_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivatelinkresources_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmregions_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models_serde.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/operations_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/options.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privateendpointconnections_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privatelinkresources_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/response_types.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/secrets_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_rfc3339.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_unix.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/vaults_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/CHANGELOG.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/LICENSE.txt create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/README.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/accounts_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/assets.json create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/autorest.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobcontainers_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobinventorypolicies_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobservices_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/build.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/ci.yml create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/client_factory.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/constants.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/deletedaccounts_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/encryptionscopes_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileservices_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileshares_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/localusers_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/managementpolicies_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models_serde.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/objectreplicationpolicies_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/operations_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/options.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privateendpointconnections_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privatelinkresources_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queue_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queueservices_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/response_types.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/skus_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/table_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/tableservices_client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/time_rfc3339.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/usages_client.go delete mode 100644 vendor/github.com/felixge/httpsnoop/.travis.yml create mode 100644 vendor/github.com/fsnotify/fsnotify/.cirrus.yml delete mode 100644 vendor/github.com/spf13/cobra/active_help.md delete mode 100644 vendor/github.com/spf13/cobra/bash_completions.md delete mode 100644 vendor/github.com/spf13/cobra/fish_completions.md delete mode 100644 vendor/github.com/spf13/cobra/powershell_completions.md delete mode 100644 vendor/github.com/spf13/cobra/projects_using_cobra.md delete mode 100644 vendor/github.com/spf13/cobra/shell_completions.md delete mode 100644 vendor/github.com/spf13/cobra/user_guide.md delete mode 100644 vendor/github.com/spf13/cobra/zsh_completions.md create mode 100644 vendor/golang.org/x/tools/internal/typesinternal/objectpath.go create mode 100644 vendor/k8s.io/cloud-provider/api/retry_error.go create mode 100644 vendor/k8s.io/cloud-provider/api/well_known_annotations.go create mode 100644 vendor/k8s.io/cloud-provider/api/well_known_taints.go create mode 100644 vendor/k8s.io/cloud-provider/node/helpers/address.go create mode 100644 vendor/k8s.io/cloud-provider/node/helpers/labels.go create mode 100644 vendor/k8s.io/cloud-provider/node/helpers/taints.go create mode 100644 vendor/k8s.io/component-helpers/node/util/cidr.go create mode 100644 vendor/k8s.io/component-helpers/node/util/conditions.go create mode 100644 vendor/k8s.io/component-helpers/node/util/hostname.go create mode 100644 vendor/k8s.io/component-helpers/node/util/ips.go create mode 100644 vendor/k8s.io/component-helpers/node/util/status.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/LICENSE create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/config_loader.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/load.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_empty.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_file.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_secret.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_yaml.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/interface.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/zz_generated_client.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/custom.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/accesscontrol.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/netip.go create mode 100644 vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/taints/taints.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE.libyaml create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/NOTICE create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/OWNERS create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/README.md create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/apic.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/decode.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/emitterc.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/encode.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/parserc.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/readerc.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/resolve.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/scannerc.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/sorter.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/writerc.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/yaml.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/yamlh.go create mode 100644 vendor/sigs.k8s.io/yaml/goyaml.v2/yamlprivateh.go diff --git a/go.mod b/go.mod index ba09d85558..45b9158a9c 100644 --- a/go.mod +++ b/go.mod @@ -15,8 +15,8 @@ require ( github.com/kubernetes-csi/csi-lib-utils v0.15.0-rc0 github.com/kubernetes-csi/csi-proxy/client v1.1.3 github.com/kubernetes-csi/external-snapshotter/client/v4 v4.2.0 - github.com/onsi/ginkgo/v2 v2.13.0 - github.com/onsi/gomega v1.28.0 + github.com/onsi/ginkgo/v2 v2.13.1 + github.com/onsi/gomega v1.30.0 github.com/pborman/uuid v1.2.1 github.com/pelletier/go-toml v1.9.5 github.com/stretchr/testify v1.8.4 @@ -38,16 +38,20 @@ require ( k8s.io/mount-utils v0.28.4 k8s.io/pod-security-admission v0.0.0 k8s.io/utils v0.0.0-20230726121419-3b25d923346b - sigs.k8s.io/cloud-provider-azure v1.27.1-0.20230825065334-8b1cf948b7ed - sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231012171618-1890d8703623 - sigs.k8s.io/yaml v1.3.0 + sigs.k8s.io/cloud-provider-azure v1.27.1-0.20231127051539-860b1f095d2b + sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231127051539-860b1f095d2b + sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231126174212-e5e88e755a1b + sigs.k8s.io/yaml v1.4.0 ) require ( github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.3.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.4.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.3.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns v1.1.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest v0.11.29 // indirect github.com/Azure/go-autorest/autorest/adal v0.9.23 // indirect @@ -70,9 +74,9 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/docker/distribution v2.8.2+incompatible // indirect github.com/emicklei/go-restful/v3 v3.10.2 // indirect - github.com/evanphx/json-patch v5.6.0+incompatible // indirect - github.com/felixge/httpsnoop v1.0.3 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/evanphx/json-patch v5.7.0+incompatible // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.3.0 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect @@ -88,7 +92,7 @@ require ( github.com/google/go-cmp v0.6.0 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/pprof v0.0.0-20230602010524-ada837c32108 // indirect - github.com/google/uuid v1.3.1 // indirect + github.com/google/uuid v1.4.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 // indirect github.com/imdario/mergo v0.3.11 // indirect @@ -112,29 +116,29 @@ require ( github.com/prometheus/client_model v0.4.0 // indirect github.com/prometheus/common v0.44.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect - github.com/spf13/cobra v1.7.0 // indirect + github.com/spf13/cobra v1.8.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stoewer/go-strcase v1.2.0 // indirect go.etcd.io/etcd/api/v3 v3.5.9 // indirect go.etcd.io/etcd/client/pkg/v3 v3.5.9 // indirect go.etcd.io/etcd/client/v3 v3.5.9 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.45.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.0 // indirect go.opentelemetry.io/otel/metric v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect go.opentelemetry.io/proto/otlp v1.0.0 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.19.0 // indirect - golang.org/x/crypto v0.14.0 // indirect + golang.org/x/crypto v0.15.0 // indirect golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect - golang.org/x/mod v0.12.0 // indirect + golang.org/x/mod v0.13.0 // indirect golang.org/x/oauth2 v0.11.0 // indirect - golang.org/x/sync v0.4.0 // indirect + golang.org/x/sync v0.5.0 // indirect golang.org/x/sys v0.14.0 // indirect - golang.org/x/term v0.13.0 // indirect - golang.org/x/text v0.13.0 // indirect - golang.org/x/time v0.3.0 // indirect - golang.org/x/tools v0.12.0 // indirect + golang.org/x/term v0.14.0 // indirect + golang.org/x/text v0.14.0 // indirect + golang.org/x/time v0.4.0 // indirect + golang.org/x/tools v0.14.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20230822172742-b8732ec3820d // indirect google.golang.org/genproto/googleapis/api v0.0.0-20230822172742-b8732ec3820d // indirect @@ -150,7 +154,7 @@ require ( k8s.io/kms v0.28.4 // indirect k8s.io/kube-openapi v0.0.0-20230717233707-2695361300d9 // indirect k8s.io/kubectl v0.0.0 // indirect - k8s.io/kubelet v0.28.0 // indirect + k8s.io/kubelet v0.28.3 // indirect sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.1.2 // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect diff --git a/go.sum b/go.sum index dde8d810c0..c5403697db 100644 --- a/go.sum +++ b/go.sum @@ -26,12 +26,16 @@ github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.0 h1:d81/ng9rET2YqdVkVwkb6EX github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.0/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.3.0 h1:qgs/VAMSR+9qFhwTw4OwF2NbVuw+2m83pVZJjqkKQMw= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.3.0/go.mod h1:uYt4CfhkJA9o0FN7jfE5minm/i4nUE4MjGUJkzB6Zs8= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.3.0 h1:U73ZEM5QTwb7x/VrXLTi+sb6Aw9DqFJxOpWuj+pDPfk= -github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.3.0/go.mod h1:WpiaNrHqgIy+P5gTYbOA/JuMmxq7uq8onUvVBybjIlI= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 h1:DWlwvVV5r/Wy1561nZ3wrpI1/vDIBRY/Wd1HWaRBZWA= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0/go.mod h1:E7ltexgRDmeJ0fJWv0D/HLwY2xbDdN+uv+X2uZtOx3w= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.4.0 h1:GYbAJIzQQBmtCx19HQur/hBT8YZxx8l6kyxcQFYMXHc= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.4.0/go.mod h1:su7G1Z0RoXhEJB4P35m34hDFNMEGik0sAUETEUuBeUA= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.1.2 h1:mLY+pNLjCUeKhgnAJWAKhEUQM+RJQo2H1fuGSw1Ky1E= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.1.2/go.mod h1:FbdwsQ2EzwvXxOPcMFYO8ogEc9uMMIj3YkmCdXdAFmk= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v2 v2.0.0 h1:PTFGRSlMKCQelWwxUyYVEUqseBJVemLyqWJjvMyt0do= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v2 v2.0.0/go.mod h1:LRr2FzBTQlONPPa5HREE5+RjSCTXl7BwOvYOaWTqCaI= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.3.0 h1:VGF4kkQEkeHq0Bp5bHDTMUiQHJRvjmdA6wjn1o2rh+s= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.3.0/go.mod h1:dE6+LTtOjte8Re4RvTi/qQcr+M5HtFAzcR8U08OeHAo= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups v1.0.0 h1:pPvTJ1dY0sA35JOeFq6TsY2xj6Z85Yo23Pj4wCCvu4o= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups v1.0.0/go.mod h1:mLfWfj8v3jfWKsL9G4eoBoXVcsqcIUTapmdKy7uGOp0= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 v4.3.0 h1:bXwSugBiSbgtz7rOtbfGf+woewp4f06orW9OP5BjHLA= @@ -40,6 +44,8 @@ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns v github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns v1.1.0/go.mod h1:y2zXtLSMM/X5Mfawq0lOftpWn3f4V6OCsRdINsvWBPI= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 h1:Dd+RhdJn0OTtVGaeDLZpcumkIVCtA/3/Fo42+eoYvVM= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0/go.mod h1:5kakwfW5CjC9KK+Q4wjXAg+ShuIm2mBMua0ZFj2C8PE= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0 h1:AifHbc4mg0x9zW52WOpKbsHaDKuRhlI7TVl47thgQ70= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0/go.mod h1:T5RfihdXtBDxt1Ch2wobif3TvzTdumDy29kahv6AV9A= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= @@ -111,7 +117,7 @@ github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -136,14 +142,14 @@ github.com/envoyproxy/protoc-gen-validate v1.0.2 h1:QkIBuU5k+x7/QXPvPPnWXWlCdaBF github.com/envoyproxy/protoc-gen-validate v1.0.2/go.mod h1:GpiZQP3dDbg4JouG/NNS7QWXpgx6x8QiMKdmN72jogE= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch v5.6.0+incompatible h1:jBYDEEiFBPxA0v50tFdvOzQQTCvpL6mnFh5mB2/l16U= -github.com/evanphx/json-patch v5.6.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= -github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/evanphx/json-patch v5.7.0+incompatible h1:vgGkfT/9f8zE6tvSCe74nfpAVDQ2tG6yudJd8LBksgI= +github.com/evanphx/json-patch v5.7.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= @@ -240,8 +246,8 @@ github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg= @@ -329,8 +335,8 @@ github.com/onsi/ginkgo/v2 v2.9.0/go.mod h1:4xkjoL/tZv4SMWeww56BU5kAt19mVB47gTWxm github.com/onsi/ginkgo/v2 v2.9.1/go.mod h1:FEcmzVcCHl+4o9bQZVab+4dC9+j+91t2FHSzmGAPfuo= github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts= github.com/onsi/ginkgo/v2 v2.9.4/go.mod h1:gCQYp2Q+kSoIj7ykSVb9nskRSsR6PUj4AiLywzIhbKM= -github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4= -github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= +github.com/onsi/ginkgo/v2 v2.13.1 h1:LNGfMbR2OVGBfXjvRZIZ2YCTQdGKtPLvuI1rMCCj3OU= +github.com/onsi/ginkgo/v2 v2.13.1/go.mod h1:XStQ8QcGwLyF4HdfcZB8SFOS/MWCgDuXMSBe6zrvLgM= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= @@ -345,8 +351,8 @@ github.com/onsi/gomega v1.27.1/go.mod h1:aHX5xOykVYzWOV4WqQy0sy8BQptgukenXpCXfad github.com/onsi/gomega v1.27.3/go.mod h1:5vG284IBtfDAmDyrK+eGyZmUgUlmi+Wngqo557cZ6Gw= github.com/onsi/gomega v1.27.4/go.mod h1:riYq/GJKh8hhoM01HN6Vmuy93AarCXCBGpvFDK3q3fQ= github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg= -github.com/onsi/gomega v1.28.0 h1:i2rg/p9n/UqIDAMFUJ6qIUUMcsqOuUHgbpbu235Vr1c= -github.com/onsi/gomega v1.28.0/go.mod h1:A1H2JE76sI14WIP57LMKj7FVfCHx3g3BcZVjJG8bjX8= +github.com/onsi/gomega v1.30.0 h1:hvMK7xYz4D3HapigLTeGdId/NcfQx1VHMJc60ew99+8= +github.com/onsi/gomega v1.30.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/selinux v1.10.0 h1:rAiKF8hTcgLI3w0DHm6i0ylVVcOrlgR1kK99DRLDhyU= @@ -384,8 +390,8 @@ github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js= github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU= @@ -436,8 +442,8 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.0 h1:PzIubN4/sjByhDRHLviCjJuweBXWFZWhghjg7cS28+M= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.0/go.mod h1:Ct6zzQEuGK3WpJs2n4dn+wfJYzd/+hNnxMRTWjGn30M= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.45.0 h1:x8Z78aZx8cOF0+Kkazoc7lwUNMGy0LrzEMxTm4BbTxg= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.45.0/go.mod h1:62CPTSry9QZtOaSsE3tOzhx6LzDhHnXJ6xHeMNNiM6Q= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.0 h1:1eHu3/pUSWaOgltNK3WJFaywKsTIr/PwvHyDmi0lQA0= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.0/go.mod h1:HyABWq60Uy1kjJSa2BVOxUVao8Cdick5AWSKPutqy6U= go.opentelemetry.io/otel v1.21.0 h1:hzLeKBZEL7Okw2mGzZ0cc4k/A7Fta0uoPgaJCr8fsFc= go.opentelemetry.io/otel v1.21.0/go.mod h1:QZzNPQPm1zLX4gZK4cMi+71eaorMSGT3A4znnUvNNEo= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.21.0 h1:cl5P5/GIfFh4t6xyruOgJP5QiA1pw4fYYdv6nc6CBWw= @@ -473,8 +479,9 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA= +golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -507,8 +514,8 @@ golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY= +golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -561,8 +568,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ= -golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -595,7 +602,6 @@ golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -617,8 +623,9 @@ golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.14.0 h1:LGK9IlZ8T9jvdy6cTdfKUCltatMFOehAQo9SRC46UQ8= +golang.org/x/term v0.14.0/go.mod h1:TySc+nGkYR6qt8km8wUhuFRTVSMIX3XPR58y2lC8vww= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -631,14 +638,16 @@ golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.4.0 h1:Z81tqI5ddIoXDPvVQ7/7CC9TnLM7ubaFG2qXYd5BbYY= +golang.org/x/time v0.4.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -671,8 +680,8 @@ golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4= -golang.org/x/tools v0.12.0 h1:YW6HUoUmYBpwSgyaGaZq1fHjrBjX1rlpZ54T6mu2kss= -golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= +golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= +golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -811,14 +820,17 @@ k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.1.2 h1:trsWhjU5jZrx6UvFu4WzQDrN7Pga4a7Qg+zcfcj64PA= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.1.2/go.mod h1:+qG7ISXqCDVVcyO8hLn12AKVYYUjM7ftlqsqmrhMZE0= -sigs.k8s.io/cloud-provider-azure v1.27.1-0.20230825065334-8b1cf948b7ed h1:tT1CT8ff+GPVYtcPxeopAnUbyapzZ0MaCFz2vgAp14U= -sigs.k8s.io/cloud-provider-azure v1.27.1-0.20230825065334-8b1cf948b7ed/go.mod h1:T86YMaSDRFlMqX5Kmb+KqeASg4Px75GQfcs0sD0yqAw= -sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231012171618-1890d8703623 h1:VM3SZMnMN5Tabj3+TyI7P/5uIiz5B2Xyknqy7NgoS7k= -sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231012171618-1890d8703623/go.mod h1:0wVQ8C8BgwINQnjLDwRB3YniyIpI3shS7Vvx2hcmDLg= +sigs.k8s.io/cloud-provider-azure v1.27.1-0.20231127051539-860b1f095d2b h1:4paOG5EgYTUwph3HTtn71/kZ6hVZzDWUNTPNByZpyu4= +sigs.k8s.io/cloud-provider-azure v1.27.1-0.20231127051539-860b1f095d2b/go.mod h1:M36MFsCkzXOA4MYSGwemzBRDfjb29LT/rmOSs2qnUxc= +sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231127051539-860b1f095d2b h1:rkR6J9cWa7QOBXOdsPt21cYt9AKYTniQer0rL+o/QIw= +sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231127051539-860b1f095d2b/go.mod h1:nSMPkB/Mk89lnZg+SOcPsnFtQCWI0puuRFZnOq42ZV8= +sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231126174212-e5e88e755a1b h1:igTDDKrYBfsO7UoHaPHtZg0p9hLQ3gAeyIP1kgtpD0k= +sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231126174212-e5e88e755a1b/go.mod h1:nhzen78LoOBrvc+754JH+kdLS+fL24s5dwtijUyZJik= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kFxnAMREiWFE= sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= +sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= +sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/pkg/azureutils/azure_disk_utils.go b/pkg/azureutils/azure_disk_utils.go index 01354b1bdd..8d369dd4a8 100644 --- a/pkg/azureutils/azure_disk_utils.go +++ b/pkg/azureutils/azure_disk_utils.go @@ -35,18 +35,18 @@ import ( "github.com/pborman/uuid" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/sets" + clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/klog/v2" - "k8s.io/mount-utils" - "k8s.io/utils/pointer" - - clientset "k8s.io/client-go/kubernetes" api "k8s.io/kubernetes/pkg/apis/core" volumeUtil "k8s.io/kubernetes/pkg/volume/util" + "k8s.io/mount-utils" + "k8s.io/utils/pointer" consts "sigs.k8s.io/azuredisk-csi-driver/pkg/azureconstants" "sigs.k8s.io/azuredisk-csi-driver/pkg/optimization" "sigs.k8s.io/azuredisk-csi-driver/pkg/util" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader" azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" azure "sigs.k8s.io/cloud-provider-azure/pkg/provider" ) @@ -172,27 +172,28 @@ func GetCloudProviderFromClient(ctx context.Context, kubeClient *clientset.Clien var config *azure.Config var fromSecret bool var err error - az := &azure.Cloud{ - InitSecretConfig: azure.InitSecretConfig{ - SecretName: secretName, - SecretNamespace: secretNamespace, - CloudConfigKey: "cloud-config", - }, - } + az := &azure.Cloud{} if kubeClient != nil { - klog.V(2).Infof("reading cloud config from secret %s/%s", az.SecretNamespace, az.SecretName) - az.KubeClient = kubeClient - config, err = az.GetConfigFromSecret() + klog.V(2).Infof("reading cloud config from secret %s/%s", secretNamespace, secretName) + config, err := configloader.Load[azure.Config](ctx, &configloader.K8sSecretLoaderConfig{ + K8sSecretConfig: configloader.K8sSecretConfig{ + SecretName: secretName, + SecretNamespace: secretNamespace, + CloudConfigKey: "cloud-config", + }, + KubeClient: kubeClient, + }, nil) + if err != nil { + klog.V(2).Infof("InitializeCloudFromSecret: failed to get cloud config from secret %s/%s: %v", secretNamespace, secretName, err) + } if err == nil && config != nil { fromSecret = true } - if err != nil { - klog.V(2).Infof("InitializeCloudFromSecret: failed to get cloud config from secret %s/%s: %v", az.SecretNamespace, az.SecretName, err) - } + az.KubeClient = kubeClient } if config == nil { - klog.V(2).Infof("could not read cloud config from secret %s/%s", az.SecretNamespace, az.SecretName) + klog.V(2).Infof("could not read cloud config from secret %s/%s", secretNamespace, secretName) credFile, ok := os.LookupEnv(consts.DefaultAzureCredentialFileEnv) if ok && strings.TrimSpace(credFile) != "" { klog.V(2).Infof("%s env var set as %v", consts.DefaultAzureCredentialFileEnv, credFile) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/CHANGELOG.md new file mode 100644 index 0000000000..279da452a3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/CHANGELOG.md @@ -0,0 +1,315 @@ +# Release History + +## 1.2.0 (2023-11-24) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + + +## 1.2.0-beta.2 (2023-10-09) +### Other Changes + +- Updated to latest `azcore` beta. + +## 1.2.0-beta.1 (2023-09-22) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. +- New enum type `ActivationStatus` with values `ActivationStatusActive`, `ActivationStatusInactive` +- New enum type `AuditLogStatus` with values `AuditLogStatusDisabled`, `AuditLogStatusEnabled` +- New enum type `AzureADAuthenticationAsArmPolicyStatus` with values `AzureADAuthenticationAsArmPolicyStatusDisabled`, `AzureADAuthenticationAsArmPolicyStatusEnabled` +- New enum type `CertificateType` with values `CertificateTypeLocalDirectory` +- New enum type `ConnectedRegistryMode` with values `ConnectedRegistryModeMirror`, `ConnectedRegistryModeReadOnly`, `ConnectedRegistryModeReadWrite`, `ConnectedRegistryModeRegistry` +- New enum type `ConnectionState` with values `ConnectionStateOffline`, `ConnectionStateOnline`, `ConnectionStateSyncing`, `ConnectionStateUnhealthy` +- New enum type `LogLevel` with values `LogLevelDebug`, `LogLevelError`, `LogLevelInformation`, `LogLevelNone`, `LogLevelWarning` +- New enum type `PackageSourceType` with values `PackageSourceTypeRemote` +- New enum type `PipelineOptions` with values `PipelineOptionsContinueOnErrors`, `PipelineOptionsDeleteSourceBlobOnSuccess`, `PipelineOptionsOverwriteBlobs`, `PipelineOptionsOverwriteTags` +- New enum type `PipelineRunSourceType` with values `PipelineRunSourceTypeAzureStorageBlob` +- New enum type `PipelineRunTargetType` with values `PipelineRunTargetTypeAzureStorageBlob` +- New enum type `PipelineSourceType` with values `PipelineSourceTypeAzureStorageBlobContainer` +- New enum type `TLSStatus` with values `TLSStatusDisabled`, `TLSStatusEnabled` +- New function `NewArchiveVersionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ArchiveVersionsClient, error)` +- New function `*ArchiveVersionsClient.BeginCreate(context.Context, string, string, string, string, string, *ArchiveVersionsClientBeginCreateOptions) (*runtime.Poller[ArchiveVersionsClientCreateResponse], error)` +- New function `*ArchiveVersionsClient.BeginDelete(context.Context, string, string, string, string, string, *ArchiveVersionsClientBeginDeleteOptions) (*runtime.Poller[ArchiveVersionsClientDeleteResponse], error)` +- New function `*ArchiveVersionsClient.Get(context.Context, string, string, string, string, string, *ArchiveVersionsClientGetOptions) (ArchiveVersionsClientGetResponse, error)` +- New function `*ArchiveVersionsClient.NewListPager(string, string, string, string, *ArchiveVersionsClientListOptions) *runtime.Pager[ArchiveVersionsClientListResponse]` +- New function `NewArchivesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ArchivesClient, error)` +- New function `*ArchivesClient.BeginCreate(context.Context, string, string, string, string, Archive, *ArchivesClientBeginCreateOptions) (*runtime.Poller[ArchivesClientCreateResponse], error)` +- New function `*ArchivesClient.BeginDelete(context.Context, string, string, string, string, *ArchivesClientBeginDeleteOptions) (*runtime.Poller[ArchivesClientDeleteResponse], error)` +- New function `*ArchivesClient.Get(context.Context, string, string, string, string, *ArchivesClientGetOptions) (ArchivesClientGetResponse, error)` +- New function `*ArchivesClient.NewListPager(string, string, string, *ArchivesClientListOptions) *runtime.Pager[ArchivesClientListResponse]` +- New function `*ArchivesClient.Update(context.Context, string, string, string, string, ArchiveUpdateParameters, *ArchivesClientUpdateOptions) (ArchivesClientUpdateResponse, error)` +- New function `*ClientFactory.NewArchiveVersionsClient() *ArchiveVersionsClient` +- New function `*ClientFactory.NewArchivesClient() *ArchivesClient` +- New function `*ClientFactory.NewConnectedRegistriesClient() *ConnectedRegistriesClient` +- New function `*ClientFactory.NewExportPipelinesClient() *ExportPipelinesClient` +- New function `*ClientFactory.NewImportPipelinesClient() *ImportPipelinesClient` +- New function `*ClientFactory.NewPipelineRunsClient() *PipelineRunsClient` +- New function `NewConnectedRegistriesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ConnectedRegistriesClient, error)` +- New function `*ConnectedRegistriesClient.BeginCreate(context.Context, string, string, string, ConnectedRegistry, *ConnectedRegistriesClientBeginCreateOptions) (*runtime.Poller[ConnectedRegistriesClientCreateResponse], error)` +- New function `*ConnectedRegistriesClient.BeginDeactivate(context.Context, string, string, string, *ConnectedRegistriesClientBeginDeactivateOptions) (*runtime.Poller[ConnectedRegistriesClientDeactivateResponse], error)` +- New function `*ConnectedRegistriesClient.BeginDelete(context.Context, string, string, string, *ConnectedRegistriesClientBeginDeleteOptions) (*runtime.Poller[ConnectedRegistriesClientDeleteResponse], error)` +- New function `*ConnectedRegistriesClient.Get(context.Context, string, string, string, *ConnectedRegistriesClientGetOptions) (ConnectedRegistriesClientGetResponse, error)` +- New function `*ConnectedRegistriesClient.NewListPager(string, string, *ConnectedRegistriesClientListOptions) *runtime.Pager[ConnectedRegistriesClientListResponse]` +- New function `*ConnectedRegistriesClient.BeginUpdate(context.Context, string, string, string, ConnectedRegistryUpdateParameters, *ConnectedRegistriesClientBeginUpdateOptions) (*runtime.Poller[ConnectedRegistriesClientUpdateResponse], error)` +- New function `NewExportPipelinesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ExportPipelinesClient, error)` +- New function `*ExportPipelinesClient.BeginCreate(context.Context, string, string, string, ExportPipeline, *ExportPipelinesClientBeginCreateOptions) (*runtime.Poller[ExportPipelinesClientCreateResponse], error)` +- New function `*ExportPipelinesClient.BeginDelete(context.Context, string, string, string, *ExportPipelinesClientBeginDeleteOptions) (*runtime.Poller[ExportPipelinesClientDeleteResponse], error)` +- New function `*ExportPipelinesClient.Get(context.Context, string, string, string, *ExportPipelinesClientGetOptions) (ExportPipelinesClientGetResponse, error)` +- New function `*ExportPipelinesClient.NewListPager(string, string, *ExportPipelinesClientListOptions) *runtime.Pager[ExportPipelinesClientListResponse]` +- New function `NewImportPipelinesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ImportPipelinesClient, error)` +- New function `*ImportPipelinesClient.BeginCreate(context.Context, string, string, string, ImportPipeline, *ImportPipelinesClientBeginCreateOptions) (*runtime.Poller[ImportPipelinesClientCreateResponse], error)` +- New function `*ImportPipelinesClient.BeginDelete(context.Context, string, string, string, *ImportPipelinesClientBeginDeleteOptions) (*runtime.Poller[ImportPipelinesClientDeleteResponse], error)` +- New function `*ImportPipelinesClient.Get(context.Context, string, string, string, *ImportPipelinesClientGetOptions) (ImportPipelinesClientGetResponse, error)` +- New function `*ImportPipelinesClient.NewListPager(string, string, *ImportPipelinesClientListOptions) *runtime.Pager[ImportPipelinesClientListResponse]` +- New function `NewPipelineRunsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*PipelineRunsClient, error)` +- New function `*PipelineRunsClient.BeginCreate(context.Context, string, string, string, PipelineRun, *PipelineRunsClientBeginCreateOptions) (*runtime.Poller[PipelineRunsClientCreateResponse], error)` +- New function `*PipelineRunsClient.BeginDelete(context.Context, string, string, string, *PipelineRunsClientBeginDeleteOptions) (*runtime.Poller[PipelineRunsClientDeleteResponse], error)` +- New function `*PipelineRunsClient.Get(context.Context, string, string, string, *PipelineRunsClientGetOptions) (PipelineRunsClientGetResponse, error)` +- New function `*PipelineRunsClient.NewListPager(string, string, *PipelineRunsClientListOptions) *runtime.Pager[PipelineRunsClientListResponse]` +- New struct `ActivationProperties` +- New struct `Archive` +- New struct `ArchiveListResult` +- New struct `ArchivePackageSourceProperties` +- New struct `ArchiveProperties` +- New struct `ArchiveUpdateParameters` +- New struct `ArchiveUpdateProperties` +- New struct `ArchiveVersion` +- New struct `ArchiveVersionListResult` +- New struct `ArchiveVersionProperties` +- New struct `AzureADAuthenticationAsArmPolicy` +- New struct `ConnectedRegistry` +- New struct `ConnectedRegistryListResult` +- New struct `ConnectedRegistryProperties` +- New struct `ConnectedRegistryUpdateParameters` +- New struct `ConnectedRegistryUpdateProperties` +- New struct `ExportPipeline` +- New struct `ExportPipelineListResult` +- New struct `ExportPipelineProperties` +- New struct `ExportPipelineTargetProperties` +- New struct `ImportPipeline` +- New struct `ImportPipelineListResult` +- New struct `ImportPipelineProperties` +- New struct `ImportPipelineSourceProperties` +- New struct `LoggingProperties` +- New struct `LoginServerProperties` +- New struct `ParentProperties` +- New struct `PipelineRun` +- New struct `PipelineRunListResult` +- New struct `PipelineRunProperties` +- New struct `PipelineRunRequest` +- New struct `PipelineRunResponse` +- New struct `PipelineRunSourceProperties` +- New struct `PipelineRunTargetProperties` +- New struct `PipelineSourceTriggerDescriptor` +- New struct `PipelineSourceTriggerProperties` +- New struct `PipelineTriggerDescriptor` +- New struct `PipelineTriggerProperties` +- New struct `ProgressProperties` +- New struct `SoftDeletePolicy` +- New struct `StatusDetailProperties` +- New struct `SyncProperties` +- New struct `SyncUpdateProperties` +- New struct `TLSCertificateProperties` +- New struct `TLSProperties` +- New field `AzureADAuthenticationAsArmPolicy`, `SoftDeletePolicy` in struct `Policies` +- New field `AnonymousPullEnabled` in struct `RegistryProperties` +- New field `AnonymousPullEnabled` in struct `RegistryPropertiesUpdateParameters` + + +## 1.1.0 (2023-09-22) +### Features Added + +- New enum type `CredentialHealthStatus` with values `CredentialHealthStatusHealthy`, `CredentialHealthStatusUnhealthy` +- New enum type `CredentialName` with values `CredentialNameCredential1` +- New function `NewCacheRulesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*CacheRulesClient, error)` +- New function `*CacheRulesClient.BeginCreate(context.Context, string, string, string, CacheRule, *CacheRulesClientBeginCreateOptions) (*runtime.Poller[CacheRulesClientCreateResponse], error)` +- New function `*CacheRulesClient.BeginDelete(context.Context, string, string, string, *CacheRulesClientBeginDeleteOptions) (*runtime.Poller[CacheRulesClientDeleteResponse], error)` +- New function `*CacheRulesClient.Get(context.Context, string, string, string, *CacheRulesClientGetOptions) (CacheRulesClientGetResponse, error)` +- New function `*CacheRulesClient.NewListPager(string, string, *CacheRulesClientListOptions) *runtime.Pager[CacheRulesClientListResponse]` +- New function `*CacheRulesClient.BeginUpdate(context.Context, string, string, string, CacheRuleUpdateParameters, *CacheRulesClientBeginUpdateOptions) (*runtime.Poller[CacheRulesClientUpdateResponse], error)` +- New function `*ClientFactory.NewCacheRulesClient() *CacheRulesClient` +- New function `*ClientFactory.NewCredentialSetsClient() *CredentialSetsClient` +- New function `NewCredentialSetsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*CredentialSetsClient, error)` +- New function `*CredentialSetsClient.BeginCreate(context.Context, string, string, string, CredentialSet, *CredentialSetsClientBeginCreateOptions) (*runtime.Poller[CredentialSetsClientCreateResponse], error)` +- New function `*CredentialSetsClient.BeginDelete(context.Context, string, string, string, *CredentialSetsClientBeginDeleteOptions) (*runtime.Poller[CredentialSetsClientDeleteResponse], error)` +- New function `*CredentialSetsClient.Get(context.Context, string, string, string, *CredentialSetsClientGetOptions) (CredentialSetsClientGetResponse, error)` +- New function `*CredentialSetsClient.NewListPager(string, string, *CredentialSetsClientListOptions) *runtime.Pager[CredentialSetsClientListResponse]` +- New function `*CredentialSetsClient.BeginUpdate(context.Context, string, string, string, CredentialSetUpdateParameters, *CredentialSetsClientBeginUpdateOptions) (*runtime.Poller[CredentialSetsClientUpdateResponse], error)` +- New struct `AuthCredential` +- New struct `CacheRule` +- New struct `CacheRuleProperties` +- New struct `CacheRuleUpdateParameters` +- New struct `CacheRuleUpdateProperties` +- New struct `CacheRulesListResult` +- New struct `CredentialHealth` +- New struct `CredentialSet` +- New struct `CredentialSetListResult` +- New struct `CredentialSetProperties` +- New struct `CredentialSetUpdateParameters` +- New struct `CredentialSetUpdateProperties` + + +## 1.0.0 (2023-03-24) +### Breaking Changes + +- Type alias `ActivationStatus` has been removed +- Type alias `AuditLogStatus` has been removed +- Type alias `AzureADAuthenticationAsArmPolicyStatus` has been removed +- Type alias `CertificateType` has been removed +- Type alias `ConnectedRegistryMode` has been removed +- Type alias `ConnectionState` has been removed +- Type alias `CredentialHealthStatus` has been removed +- Type alias `CredentialName` has been removed +- Type alias `LogLevel` has been removed +- Type alias `PipelineOptions` has been removed +- Type alias `PipelineRunSourceType` has been removed +- Type alias `PipelineRunTargetType` has been removed +- Type alias `PipelineSourceType` has been removed +- Type alias `TLSStatus` has been removed +- Function `NewCacheRulesClient` has been removed +- Function `*CacheRulesClient.BeginCreate` has been removed +- Function `*CacheRulesClient.BeginDelete` has been removed +- Function `*CacheRulesClient.Get` has been removed +- Function `*CacheRulesClient.NewListPager` has been removed +- Function `*CacheRulesClient.BeginUpdate` has been removed +- Function `NewConnectedRegistriesClient` has been removed +- Function `*ConnectedRegistriesClient.BeginCreate` has been removed +- Function `*ConnectedRegistriesClient.BeginDeactivate` has been removed +- Function `*ConnectedRegistriesClient.BeginDelete` has been removed +- Function `*ConnectedRegistriesClient.Get` has been removed +- Function `*ConnectedRegistriesClient.NewListPager` has been removed +- Function `*ConnectedRegistriesClient.BeginUpdate` has been removed +- Function `NewCredentialSetsClient` has been removed +- Function `*CredentialSetsClient.BeginCreate` has been removed +- Function `*CredentialSetsClient.BeginDelete` has been removed +- Function `*CredentialSetsClient.Get` has been removed +- Function `*CredentialSetsClient.NewListPager` has been removed +- Function `*CredentialSetsClient.BeginUpdate` has been removed +- Function `NewExportPipelinesClient` has been removed +- Function `*ExportPipelinesClient.BeginCreate` has been removed +- Function `*ExportPipelinesClient.BeginDelete` has been removed +- Function `*ExportPipelinesClient.Get` has been removed +- Function `*ExportPipelinesClient.NewListPager` has been removed +- Function `NewImportPipelinesClient` has been removed +- Function `*ImportPipelinesClient.BeginCreate` has been removed +- Function `*ImportPipelinesClient.BeginDelete` has been removed +- Function `*ImportPipelinesClient.Get` has been removed +- Function `*ImportPipelinesClient.NewListPager` has been removed +- Function `NewPipelineRunsClient` has been removed +- Function `*PipelineRunsClient.BeginCreate` has been removed +- Function `*PipelineRunsClient.BeginDelete` has been removed +- Function `*PipelineRunsClient.Get` has been removed +- Function `*PipelineRunsClient.NewListPager` has been removed +- Struct `ActivationProperties` has been removed +- Struct `AuthCredential` has been removed +- Struct `AzureADAuthenticationAsArmPolicy` has been removed +- Struct `CacheRule` has been removed +- Struct `CacheRuleProperties` has been removed +- Struct `CacheRuleUpdateParameters` has been removed +- Struct `CacheRuleUpdateProperties` has been removed +- Struct `CacheRulesClient` has been removed +- Struct `CacheRulesListResult` has been removed +- Struct `ConnectedRegistriesClient` has been removed +- Struct `ConnectedRegistry` has been removed +- Struct `ConnectedRegistryListResult` has been removed +- Struct `ConnectedRegistryProperties` has been removed +- Struct `ConnectedRegistryUpdateParameters` has been removed +- Struct `ConnectedRegistryUpdateProperties` has been removed +- Struct `CredentialHealth` has been removed +- Struct `CredentialSet` has been removed +- Struct `CredentialSetListResult` has been removed +- Struct `CredentialSetProperties` has been removed +- Struct `CredentialSetUpdateParameters` has been removed +- Struct `CredentialSetUpdateProperties` has been removed +- Struct `CredentialSetsClient` has been removed +- Struct `ExportPipeline` has been removed +- Struct `ExportPipelineListResult` has been removed +- Struct `ExportPipelineProperties` has been removed +- Struct `ExportPipelineTargetProperties` has been removed +- Struct `ExportPipelinesClient` has been removed +- Struct `ImportPipeline` has been removed +- Struct `ImportPipelineListResult` has been removed +- Struct `ImportPipelineProperties` has been removed +- Struct `ImportPipelineSourceProperties` has been removed +- Struct `ImportPipelinesClient` has been removed +- Struct `LoggingProperties` has been removed +- Struct `LoginServerProperties` has been removed +- Struct `ParentProperties` has been removed +- Struct `PipelineRun` has been removed +- Struct `PipelineRunListResult` has been removed +- Struct `PipelineRunProperties` has been removed +- Struct `PipelineRunRequest` has been removed +- Struct `PipelineRunResponse` has been removed +- Struct `PipelineRunSourceProperties` has been removed +- Struct `PipelineRunTargetProperties` has been removed +- Struct `PipelineRunsClient` has been removed +- Struct `PipelineSourceTriggerDescriptor` has been removed +- Struct `PipelineSourceTriggerProperties` has been removed +- Struct `PipelineTriggerDescriptor` has been removed +- Struct `PipelineTriggerProperties` has been removed +- Struct `ProgressProperties` has been removed +- Struct `SoftDeletePolicy` has been removed +- Struct `StatusDetailProperties` has been removed +- Struct `SyncProperties` has been removed +- Struct `SyncUpdateProperties` has been removed +- Struct `TLSCertificateProperties` has been removed +- Struct `TLSProperties` has been removed +- Field `AzureADAuthenticationAsArmPolicy` of struct `Policies` has been removed +- Field `SoftDeletePolicy` of struct `Policies` has been removed +- Field `AnonymousPullEnabled` of struct `RegistryProperties` has been removed +- Field `AnonymousPullEnabled` of struct `RegistryPropertiesUpdateParameters` has been removed + +### Features Added + +- New struct `ClientFactory` which is a client factory used to create any client in this module + + +## 0.7.0 (2023-02-24) +### Features Added + +- New type alias `CredentialHealthStatus` with values `CredentialHealthStatusHealthy`, `CredentialHealthStatusUnhealthy` +- New type alias `CredentialName` with values `CredentialNameCredential1` +- New function `NewCacheRulesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*CacheRulesClient, error)` +- New function `*CacheRulesClient.BeginCreate(context.Context, string, string, string, CacheRule, *CacheRulesClientBeginCreateOptions) (*runtime.Poller[CacheRulesClientCreateResponse], error)` +- New function `*CacheRulesClient.BeginDelete(context.Context, string, string, string, *CacheRulesClientBeginDeleteOptions) (*runtime.Poller[CacheRulesClientDeleteResponse], error)` +- New function `*CacheRulesClient.Get(context.Context, string, string, string, *CacheRulesClientGetOptions) (CacheRulesClientGetResponse, error)` +- New function `*CacheRulesClient.NewListPager(string, string, *CacheRulesClientListOptions) *runtime.Pager[CacheRulesClientListResponse]` +- New function `*CacheRulesClient.BeginUpdate(context.Context, string, string, string, CacheRuleUpdateParameters, *CacheRulesClientBeginUpdateOptions) (*runtime.Poller[CacheRulesClientUpdateResponse], error)` +- New function `NewCredentialSetsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*CredentialSetsClient, error)` +- New function `*CredentialSetsClient.BeginCreate(context.Context, string, string, string, CredentialSet, *CredentialSetsClientBeginCreateOptions) (*runtime.Poller[CredentialSetsClientCreateResponse], error)` +- New function `*CredentialSetsClient.BeginDelete(context.Context, string, string, string, *CredentialSetsClientBeginDeleteOptions) (*runtime.Poller[CredentialSetsClientDeleteResponse], error)` +- New function `*CredentialSetsClient.Get(context.Context, string, string, string, *CredentialSetsClientGetOptions) (CredentialSetsClientGetResponse, error)` +- New function `*CredentialSetsClient.NewListPager(string, string, *CredentialSetsClientListOptions) *runtime.Pager[CredentialSetsClientListResponse]` +- New function `*CredentialSetsClient.BeginUpdate(context.Context, string, string, string, CredentialSetUpdateParameters, *CredentialSetsClientBeginUpdateOptions) (*runtime.Poller[CredentialSetsClientUpdateResponse], error)` +- New struct `AuthCredential` +- New struct `CacheRule` +- New struct `CacheRuleProperties` +- New struct `CacheRuleUpdateParameters` +- New struct `CacheRuleUpdateProperties` +- New struct `CacheRulesClient` +- New struct `CacheRulesClientCreateResponse` +- New struct `CacheRulesClientDeleteResponse` +- New struct `CacheRulesClientListResponse` +- New struct `CacheRulesClientUpdateResponse` +- New struct `CacheRulesListResult` +- New struct `CredentialHealth` +- New struct `CredentialSet` +- New struct `CredentialSetListResult` +- New struct `CredentialSetProperties` +- New struct `CredentialSetUpdateParameters` +- New struct `CredentialSetUpdateProperties` +- New struct `CredentialSetsClient` +- New struct `CredentialSetsClientCreateResponse` +- New struct `CredentialSetsClientDeleteResponse` +- New struct `CredentialSetsClientListResponse` +- New struct `CredentialSetsClientUpdateResponse` + + +## 0.6.0 (2022-05-17) + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html) since version 0.6.0, which contains breaking changes. + +To migrate the existing applications to the latest version, please refer to [Migration Guide](https://aka.ms/azsdk/go/mgmt/migration). + +To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt). \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/LICENSE.txt new file mode 100644 index 0000000000..dc0c2ffb3d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/README.md new file mode 100644 index 0000000000..0a21899c10 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/README.md @@ -0,0 +1,99 @@ +# Azure Container Registry Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry) + +The `armcontainerregistry` module provides operations for working with Azure Container Registry. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/containerregistry/armcontainerregistry) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 or above (You could download and install the latest version of Go from [here](https://go.dev/doc/install). It will replace the existing Go on your machine. If you want to install multiple Go versions on the same machine, you could refer this [doc](https://go.dev/doc/manage-install).) + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Container Registry module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Container Registry. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Client Factory + +Azure Container Registry module consists of one or more clients. We provide a client factory which could be used to create any client in this module. + +```go +clientFactory, err := armcontainerregistry.NewClientFactory(, cred, nil) +``` + +You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +```go +options := arm.ClientOptions { + ClientOptions: azcore.ClientOptions { + Cloud: cloud.AzureChina, + }, +} +clientFactory, err := armcontainerregistry.NewClientFactory(, cred, &options) +``` + +## Clients + +A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. + +```go +client := clientFactory.NewImportPipelinesClient() +``` + +## Fakes + +The fake package contains types used for constructing in-memory fake servers used in unit tests. +This allows writing tests to cover various success/error conditions without the need for connecting to a live service. + +Please see https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/samples/fakes for details and examples on how to use fakes. + +## More sample code + +- [Container Registry](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/containerregistry/registry) +- [Replication](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/containerregistry/replication) +- [Container Task](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/containerregistry/task) +- [Container Token](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/containerregistry/token) + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Container Registry` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/agentpools_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/agentpools_client.go new file mode 100644 index 0000000000..07a0330691 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/agentpools_client.go @@ -0,0 +1,495 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AgentPoolsClient contains the methods for the AgentPools group. +// Don't use this type directly, use NewAgentPoolsClient() instead. +type AgentPoolsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAgentPoolsClient creates a new instance of AgentPoolsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewAgentPoolsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AgentPoolsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AgentPoolsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates an agent pool for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - agentPoolName - The name of the agent pool. +// - agentPool - The parameters of an agent pool that needs to scheduled. +// - options - AgentPoolsClientBeginCreateOptions contains the optional parameters for the AgentPoolsClient.BeginCreate method. +func (client *AgentPoolsClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, agentPool AgentPool, options *AgentPoolsClientBeginCreateOptions) (*runtime.Poller[AgentPoolsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, agentPoolName, agentPool, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentPoolsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentPoolsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates an agent pool for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *AgentPoolsClient) create(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, agentPool AgentPool, options *AgentPoolsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "AgentPoolsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, agentPoolName, agentPool, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *AgentPoolsClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, agentPool AgentPool, options *AgentPoolsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/agentPools/{agentPoolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if agentPoolName == "" { + return nil, errors.New("parameter agentPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, agentPool); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a specified agent pool resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - agentPoolName - The name of the agent pool. +// - options - AgentPoolsClientBeginDeleteOptions contains the optional parameters for the AgentPoolsClient.BeginDelete method. +func (client *AgentPoolsClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*runtime.Poller[AgentPoolsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, agentPoolName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentPoolsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentPoolsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a specified agent pool resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *AgentPoolsClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AgentPoolsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, agentPoolName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/agentPools/{agentPoolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if agentPoolName == "" { + return nil, errors.New("parameter agentPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the detailed information for a given agent pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - agentPoolName - The name of the agent pool. +// - options - AgentPoolsClientGetOptions contains the optional parameters for the AgentPoolsClient.Get method. +func (client *AgentPoolsClient) Get(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientGetOptions) (AgentPoolsClientGetResponse, error) { + var err error + const operationName = "AgentPoolsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, agentPoolName, options) + if err != nil { + return AgentPoolsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentPoolsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentPoolsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AgentPoolsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/agentPools/{agentPoolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if agentPoolName == "" { + return nil, errors.New("parameter agentPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AgentPoolsClient) getHandleResponse(resp *http.Response) (AgentPoolsClientGetResponse, error) { + result := AgentPoolsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentPool); err != nil { + return AgentPoolsClientGetResponse{}, err + } + return result, nil +} + +// GetQueueStatus - Gets the count of queued runs for a given agent pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - agentPoolName - The name of the agent pool. +// - options - AgentPoolsClientGetQueueStatusOptions contains the optional parameters for the AgentPoolsClient.GetQueueStatus +// method. +func (client *AgentPoolsClient) GetQueueStatus(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientGetQueueStatusOptions) (AgentPoolsClientGetQueueStatusResponse, error) { + var err error + const operationName = "AgentPoolsClient.GetQueueStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getQueueStatusCreateRequest(ctx, resourceGroupName, registryName, agentPoolName, options) + if err != nil { + return AgentPoolsClientGetQueueStatusResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentPoolsClientGetQueueStatusResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentPoolsClientGetQueueStatusResponse{}, err + } + resp, err := client.getQueueStatusHandleResponse(httpResp) + return resp, err +} + +// getQueueStatusCreateRequest creates the GetQueueStatus request. +func (client *AgentPoolsClient) getQueueStatusCreateRequest(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, options *AgentPoolsClientGetQueueStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/agentPools/{agentPoolName}/listQueueStatus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if agentPoolName == "" { + return nil, errors.New("parameter agentPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getQueueStatusHandleResponse handles the GetQueueStatus response. +func (client *AgentPoolsClient) getQueueStatusHandleResponse(resp *http.Response) (AgentPoolsClientGetQueueStatusResponse, error) { + result := AgentPoolsClientGetQueueStatusResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentPoolQueueStatus); err != nil { + return AgentPoolsClientGetQueueStatusResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the agent pools for a specified container registry. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - options - AgentPoolsClientListOptions contains the optional parameters for the AgentPoolsClient.NewListPager method. +func (client *AgentPoolsClient) NewListPager(resourceGroupName string, registryName string, options *AgentPoolsClientListOptions) *runtime.Pager[AgentPoolsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AgentPoolsClientListResponse]{ + More: func(page AgentPoolsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AgentPoolsClientListResponse) (AgentPoolsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AgentPoolsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return AgentPoolsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AgentPoolsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *AgentPoolsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/agentPools" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AgentPoolsClient) listHandleResponse(resp *http.Response) (AgentPoolsClientListResponse, error) { + result := AgentPoolsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentPoolListResult); err != nil { + return AgentPoolsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates an agent pool with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - agentPoolName - The name of the agent pool. +// - updateParameters - The parameters for updating an agent pool. +// - options - AgentPoolsClientBeginUpdateOptions contains the optional parameters for the AgentPoolsClient.BeginUpdate method. +func (client *AgentPoolsClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, updateParameters AgentPoolUpdateParameters, options *AgentPoolsClientBeginUpdateOptions) (*runtime.Poller[AgentPoolsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, agentPoolName, updateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentPoolsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentPoolsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates an agent pool with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *AgentPoolsClient) update(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, updateParameters AgentPoolUpdateParameters, options *AgentPoolsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AgentPoolsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, agentPoolName, updateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AgentPoolsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, agentPoolName string, updateParameters AgentPoolUpdateParameters, options *AgentPoolsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/agentPools/{agentPoolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if agentPoolName == "" { + return nil, errors.New("parameter agentPoolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, updateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/assets.json new file mode 100644 index 0000000000..545db436e6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "go", + "TagPrefix": "go/resourcemanager/containerregistry/armcontainerregistry", + "Tag": "go/resourcemanager/containerregistry/armcontainerregistry_9fcf492e3c" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/autorest.md new file mode 100644 index 0000000000..726e7154a5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/autorest.md @@ -0,0 +1,13 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/bbe1ea8bf5aa6cfbfa8855e03dbb9a93f8266bcd/specification/containerregistry/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/bbe1ea8bf5aa6cfbfa8855e03dbb9a93f8266bcd/specification/containerregistry/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 1.2.0 +tag: package-2023-07 +``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/build.go new file mode 100644 index 0000000000..f0c69abc5c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -removeUnreferencedTypes resourcemanager/containerregistry/armcontainerregistry + +package armcontainerregistry diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/cacherules_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/cacherules_client.go new file mode 100644 index 0000000000..21ac29dfd2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/cacherules_client.go @@ -0,0 +1,428 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CacheRulesClient contains the methods for the CacheRules group. +// Don't use this type directly, use NewCacheRulesClient() instead. +type CacheRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCacheRulesClient creates a new instance of CacheRulesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewCacheRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CacheRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CacheRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a cache rule for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - cacheRuleName - The name of the cache rule. +// - cacheRuleCreateParameters - The parameters for creating a cache rule. +// - options - CacheRulesClientBeginCreateOptions contains the optional parameters for the CacheRulesClient.BeginCreate method. +func (client *CacheRulesClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, cacheRuleCreateParameters CacheRule, options *CacheRulesClientBeginCreateOptions) (*runtime.Poller[CacheRulesClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, cacheRuleName, cacheRuleCreateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CacheRulesClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CacheRulesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a cache rule for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *CacheRulesClient) create(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, cacheRuleCreateParameters CacheRule, options *CacheRulesClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "CacheRulesClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, cacheRuleName, cacheRuleCreateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *CacheRulesClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, cacheRuleCreateParameters CacheRule, options *CacheRulesClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/cacheRules/{cacheRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if cacheRuleName == "" { + return nil, errors.New("parameter cacheRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cacheRuleName}", url.PathEscape(cacheRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, cacheRuleCreateParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a cache rule resource from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - cacheRuleName - The name of the cache rule. +// - options - CacheRulesClientBeginDeleteOptions contains the optional parameters for the CacheRulesClient.BeginDelete method. +func (client *CacheRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, options *CacheRulesClientBeginDeleteOptions) (*runtime.Poller[CacheRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, cacheRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CacheRulesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CacheRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a cache rule resource from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *CacheRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, options *CacheRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CacheRulesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, cacheRuleName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CacheRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, options *CacheRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/cacheRules/{cacheRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if cacheRuleName == "" { + return nil, errors.New("parameter cacheRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cacheRuleName}", url.PathEscape(cacheRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the properties of the specified cache rule resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - cacheRuleName - The name of the cache rule. +// - options - CacheRulesClientGetOptions contains the optional parameters for the CacheRulesClient.Get method. +func (client *CacheRulesClient) Get(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, options *CacheRulesClientGetOptions) (CacheRulesClientGetResponse, error) { + var err error + const operationName = "CacheRulesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, cacheRuleName, options) + if err != nil { + return CacheRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CacheRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CacheRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CacheRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, options *CacheRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/cacheRules/{cacheRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if cacheRuleName == "" { + return nil, errors.New("parameter cacheRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cacheRuleName}", url.PathEscape(cacheRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CacheRulesClient) getHandleResponse(resp *http.Response) (CacheRulesClientGetResponse, error) { + result := CacheRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CacheRule); err != nil { + return CacheRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all cache rule resources for the specified container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - CacheRulesClientListOptions contains the optional parameters for the CacheRulesClient.NewListPager method. +func (client *CacheRulesClient) NewListPager(resourceGroupName string, registryName string, options *CacheRulesClientListOptions) *runtime.Pager[CacheRulesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CacheRulesClientListResponse]{ + More: func(page CacheRulesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CacheRulesClientListResponse) (CacheRulesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CacheRulesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return CacheRulesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CacheRulesClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *CacheRulesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/cacheRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CacheRulesClient) listHandleResponse(resp *http.Response) (CacheRulesClientListResponse, error) { + result := CacheRulesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CacheRulesListResult); err != nil { + return CacheRulesClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a cache rule for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - cacheRuleName - The name of the cache rule. +// - cacheRuleUpdateParameters - The parameters for updating a cache rule. +// - options - CacheRulesClientBeginUpdateOptions contains the optional parameters for the CacheRulesClient.BeginUpdate method. +func (client *CacheRulesClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, cacheRuleUpdateParameters CacheRuleUpdateParameters, options *CacheRulesClientBeginUpdateOptions) (*runtime.Poller[CacheRulesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, cacheRuleName, cacheRuleUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CacheRulesClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CacheRulesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a cache rule for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *CacheRulesClient) update(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, cacheRuleUpdateParameters CacheRuleUpdateParameters, options *CacheRulesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CacheRulesClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, cacheRuleName, cacheRuleUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CacheRulesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, cacheRuleName string, cacheRuleUpdateParameters CacheRuleUpdateParameters, options *CacheRulesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/cacheRules/{cacheRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if cacheRuleName == "" { + return nil, errors.New("parameter cacheRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cacheRuleName}", url.PathEscape(cacheRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, cacheRuleUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/ci.yml new file mode 100644 index 0000000000..dc1b35e2f1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/ci.yml @@ -0,0 +1,28 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/containerregistry/armcontainerregistry/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/containerregistry/armcontainerregistry/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/containerregistry/armcontainerregistry' diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/client_factory.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/client_factory.go new file mode 100644 index 0000000000..1444ae659c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/client_factory.go @@ -0,0 +1,116 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + credential azcore.TokenCredential + options *arm.ClientOptions +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + _, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, credential: credential, + options: options.Clone(), + }, nil +} + +// NewAgentPoolsClient creates a new instance of AgentPoolsClient. +func (c *ClientFactory) NewAgentPoolsClient() *AgentPoolsClient { + subClient, _ := NewAgentPoolsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCacheRulesClient creates a new instance of CacheRulesClient. +func (c *ClientFactory) NewCacheRulesClient() *CacheRulesClient { + subClient, _ := NewCacheRulesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewCredentialSetsClient creates a new instance of CredentialSetsClient. +func (c *ClientFactory) NewCredentialSetsClient() *CredentialSetsClient { + subClient, _ := NewCredentialSetsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + subClient, _ := NewOperationsClient(c.credential, c.options) + return subClient +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient. +func (c *ClientFactory) NewPrivateEndpointConnectionsClient() *PrivateEndpointConnectionsClient { + subClient, _ := NewPrivateEndpointConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRegistriesClient creates a new instance of RegistriesClient. +func (c *ClientFactory) NewRegistriesClient() *RegistriesClient { + subClient, _ := NewRegistriesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewReplicationsClient creates a new instance of ReplicationsClient. +func (c *ClientFactory) NewReplicationsClient() *ReplicationsClient { + subClient, _ := NewReplicationsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewRunsClient creates a new instance of RunsClient. +func (c *ClientFactory) NewRunsClient() *RunsClient { + subClient, _ := NewRunsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewScopeMapsClient creates a new instance of ScopeMapsClient. +func (c *ClientFactory) NewScopeMapsClient() *ScopeMapsClient { + subClient, _ := NewScopeMapsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewTaskRunsClient creates a new instance of TaskRunsClient. +func (c *ClientFactory) NewTaskRunsClient() *TaskRunsClient { + subClient, _ := NewTaskRunsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewTasksClient creates a new instance of TasksClient. +func (c *ClientFactory) NewTasksClient() *TasksClient { + subClient, _ := NewTasksClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewTokensClient creates a new instance of TokensClient. +func (c *ClientFactory) NewTokensClient() *TokensClient { + subClient, _ := NewTokensClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewWebhooksClient creates a new instance of WebhooksClient. +func (c *ClientFactory) NewWebhooksClient() *WebhooksClient { + subClient, _ := NewWebhooksClient(c.subscriptionID, c.credential, c.options) + return subClient +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/constants.go new file mode 100644 index 0000000000..65bc6456a9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/constants.go @@ -0,0 +1,760 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry" + moduleVersion = "v1.2.0" +) + +// Action - The action of IP ACL rule. +type Action string + +const ( + ActionAllow Action = "Allow" +) + +// PossibleActionValues returns the possible values for the Action const type. +func PossibleActionValues() []Action { + return []Action{ + ActionAllow, + } +} + +// ActionsRequired - A message indicating if changes on the service provider require any updates on the consumer. +type ActionsRequired string + +const ( + ActionsRequiredNone ActionsRequired = "None" + ActionsRequiredRecreate ActionsRequired = "Recreate" +) + +// PossibleActionsRequiredValues returns the possible values for the ActionsRequired const type. +func PossibleActionsRequiredValues() []ActionsRequired { + return []ActionsRequired{ + ActionsRequiredNone, + ActionsRequiredRecreate, + } +} + +// Architecture - The OS architecture. +type Architecture string + +const ( + ArchitectureAmd64 Architecture = "amd64" + ArchitectureArm Architecture = "arm" + ArchitectureArm64 Architecture = "arm64" + ArchitectureThreeHundredEightySix Architecture = "386" + ArchitectureX86 Architecture = "x86" +) + +// PossibleArchitectureValues returns the possible values for the Architecture const type. +func PossibleArchitectureValues() []Architecture { + return []Architecture{ + ArchitectureAmd64, + ArchitectureArm, + ArchitectureArm64, + ArchitectureThreeHundredEightySix, + ArchitectureX86, + } +} + +// BaseImageDependencyType - The type of the base image dependency. +type BaseImageDependencyType string + +const ( + BaseImageDependencyTypeBuildTime BaseImageDependencyType = "BuildTime" + BaseImageDependencyTypeRunTime BaseImageDependencyType = "RunTime" +) + +// PossibleBaseImageDependencyTypeValues returns the possible values for the BaseImageDependencyType const type. +func PossibleBaseImageDependencyTypeValues() []BaseImageDependencyType { + return []BaseImageDependencyType{ + BaseImageDependencyTypeBuildTime, + BaseImageDependencyTypeRunTime, + } +} + +// BaseImageTriggerType - The type of the auto trigger for base image dependency updates. +type BaseImageTriggerType string + +const ( + BaseImageTriggerTypeAll BaseImageTriggerType = "All" + BaseImageTriggerTypeRuntime BaseImageTriggerType = "Runtime" +) + +// PossibleBaseImageTriggerTypeValues returns the possible values for the BaseImageTriggerType const type. +func PossibleBaseImageTriggerTypeValues() []BaseImageTriggerType { + return []BaseImageTriggerType{ + BaseImageTriggerTypeAll, + BaseImageTriggerTypeRuntime, + } +} + +// ConnectionStatus - The private link service connection status. +type ConnectionStatus string + +const ( + ConnectionStatusApproved ConnectionStatus = "Approved" + ConnectionStatusDisconnected ConnectionStatus = "Disconnected" + ConnectionStatusPending ConnectionStatus = "Pending" + ConnectionStatusRejected ConnectionStatus = "Rejected" +) + +// PossibleConnectionStatusValues returns the possible values for the ConnectionStatus const type. +func PossibleConnectionStatusValues() []ConnectionStatus { + return []ConnectionStatus{ + ConnectionStatusApproved, + ConnectionStatusDisconnected, + ConnectionStatusPending, + ConnectionStatusRejected, + } +} + +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// CredentialHealthStatus - The health status of credential. +type CredentialHealthStatus string + +const ( + CredentialHealthStatusHealthy CredentialHealthStatus = "Healthy" + CredentialHealthStatusUnhealthy CredentialHealthStatus = "Unhealthy" +) + +// PossibleCredentialHealthStatusValues returns the possible values for the CredentialHealthStatus const type. +func PossibleCredentialHealthStatusValues() []CredentialHealthStatus { + return []CredentialHealthStatus{ + CredentialHealthStatusHealthy, + CredentialHealthStatusUnhealthy, + } +} + +// CredentialName - The name of the credential. +type CredentialName string + +const ( + CredentialNameCredential1 CredentialName = "Credential1" +) + +// PossibleCredentialNameValues returns the possible values for the CredentialName const type. +func PossibleCredentialNameValues() []CredentialName { + return []CredentialName{ + CredentialNameCredential1, + } +} + +// DefaultAction - The default action of allow or deny when no other rules match. +type DefaultAction string + +const ( + DefaultActionAllow DefaultAction = "Allow" + DefaultActionDeny DefaultAction = "Deny" +) + +// PossibleDefaultActionValues returns the possible values for the DefaultAction const type. +func PossibleDefaultActionValues() []DefaultAction { + return []DefaultAction{ + DefaultActionAllow, + DefaultActionDeny, + } +} + +// EncryptionStatus - Indicates whether or not the encryption is enabled for container registry. +type EncryptionStatus string + +const ( + EncryptionStatusDisabled EncryptionStatus = "disabled" + EncryptionStatusEnabled EncryptionStatus = "enabled" +) + +// PossibleEncryptionStatusValues returns the possible values for the EncryptionStatus const type. +func PossibleEncryptionStatusValues() []EncryptionStatus { + return []EncryptionStatus{ + EncryptionStatusDisabled, + EncryptionStatusEnabled, + } +} + +// ExportPolicyStatus - The value that indicates whether the policy is enabled or not. +type ExportPolicyStatus string + +const ( + ExportPolicyStatusDisabled ExportPolicyStatus = "disabled" + ExportPolicyStatusEnabled ExportPolicyStatus = "enabled" +) + +// PossibleExportPolicyStatusValues returns the possible values for the ExportPolicyStatus const type. +func PossibleExportPolicyStatusValues() []ExportPolicyStatus { + return []ExportPolicyStatus{ + ExportPolicyStatusDisabled, + ExportPolicyStatusEnabled, + } +} + +// ImportMode - When Force, any existing target tags will be overwritten. When NoForce, any existing target tags will fail +// the operation before any copying begins. +type ImportMode string + +const ( + ImportModeForce ImportMode = "Force" + ImportModeNoForce ImportMode = "NoForce" +) + +// PossibleImportModeValues returns the possible values for the ImportMode const type. +func PossibleImportModeValues() []ImportMode { + return []ImportMode{ + ImportModeForce, + ImportModeNoForce, + } +} + +// LastModifiedByType - The type of identity that last modified the resource. +type LastModifiedByType string + +const ( + LastModifiedByTypeApplication LastModifiedByType = "Application" + LastModifiedByTypeKey LastModifiedByType = "Key" + LastModifiedByTypeManagedIdentity LastModifiedByType = "ManagedIdentity" + LastModifiedByTypeUser LastModifiedByType = "User" +) + +// PossibleLastModifiedByTypeValues returns the possible values for the LastModifiedByType const type. +func PossibleLastModifiedByTypeValues() []LastModifiedByType { + return []LastModifiedByType{ + LastModifiedByTypeApplication, + LastModifiedByTypeKey, + LastModifiedByTypeManagedIdentity, + LastModifiedByTypeUser, + } +} + +// NetworkRuleBypassOptions - Whether to allow trusted Azure services to access a network restricted registry. +type NetworkRuleBypassOptions string + +const ( + NetworkRuleBypassOptionsAzureServices NetworkRuleBypassOptions = "AzureServices" + NetworkRuleBypassOptionsNone NetworkRuleBypassOptions = "None" +) + +// PossibleNetworkRuleBypassOptionsValues returns the possible values for the NetworkRuleBypassOptions const type. +func PossibleNetworkRuleBypassOptionsValues() []NetworkRuleBypassOptions { + return []NetworkRuleBypassOptions{ + NetworkRuleBypassOptionsAzureServices, + NetworkRuleBypassOptionsNone, + } +} + +// OS - The OS of agent machine +type OS string + +const ( + OSLinux OS = "Linux" + OSWindows OS = "Windows" +) + +// PossibleOSValues returns the possible values for the OS const type. +func PossibleOSValues() []OS { + return []OS{ + OSLinux, + OSWindows, + } +} + +// PasswordName - The password name. +type PasswordName string + +const ( + PasswordNamePassword PasswordName = "password" + PasswordNamePassword2 PasswordName = "password2" +) + +// PossiblePasswordNameValues returns the possible values for the PasswordName const type. +func PossiblePasswordNameValues() []PasswordName { + return []PasswordName{ + PasswordNamePassword, + PasswordNamePassword2, + } +} + +// PolicyStatus - The value that indicates whether the policy is enabled or not. +type PolicyStatus string + +const ( + PolicyStatusDisabled PolicyStatus = "disabled" + PolicyStatusEnabled PolicyStatus = "enabled" +) + +// PossiblePolicyStatusValues returns the possible values for the PolicyStatus const type. +func PossiblePolicyStatusValues() []PolicyStatus { + return []PolicyStatus{ + PolicyStatusDisabled, + PolicyStatusEnabled, + } +} + +// ProvisioningState - The provisioning state of this agent pool +type ProvisioningState string + +const ( + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCanceled, + ProvisioningStateCreating, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// PublicNetworkAccess - Whether or not public network access is allowed for the container registry. +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// RegistryUsageUnit - The unit of measurement. +type RegistryUsageUnit string + +const ( + RegistryUsageUnitBytes RegistryUsageUnit = "Bytes" + RegistryUsageUnitCount RegistryUsageUnit = "Count" +) + +// PossibleRegistryUsageUnitValues returns the possible values for the RegistryUsageUnit const type. +func PossibleRegistryUsageUnitValues() []RegistryUsageUnit { + return []RegistryUsageUnit{ + RegistryUsageUnitBytes, + RegistryUsageUnitCount, + } +} + +// ResourceIdentityType - The identity type. +type ResourceIdentityType string + +const ( + ResourceIdentityTypeNone ResourceIdentityType = "None" + ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" + ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" + ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" +) + +// PossibleResourceIdentityTypeValues returns the possible values for the ResourceIdentityType const type. +func PossibleResourceIdentityTypeValues() []ResourceIdentityType { + return []ResourceIdentityType{ + ResourceIdentityTypeNone, + ResourceIdentityTypeSystemAssigned, + ResourceIdentityTypeSystemAssignedUserAssigned, + ResourceIdentityTypeUserAssigned, + } +} + +// RunStatus - The current status of the run. +type RunStatus string + +const ( + RunStatusCanceled RunStatus = "Canceled" + RunStatusError RunStatus = "Error" + RunStatusFailed RunStatus = "Failed" + RunStatusQueued RunStatus = "Queued" + RunStatusRunning RunStatus = "Running" + RunStatusStarted RunStatus = "Started" + RunStatusSucceeded RunStatus = "Succeeded" + RunStatusTimeout RunStatus = "Timeout" +) + +// PossibleRunStatusValues returns the possible values for the RunStatus const type. +func PossibleRunStatusValues() []RunStatus { + return []RunStatus{ + RunStatusCanceled, + RunStatusError, + RunStatusFailed, + RunStatusQueued, + RunStatusRunning, + RunStatusStarted, + RunStatusSucceeded, + RunStatusTimeout, + } +} + +// RunType - The type of run. +type RunType string + +const ( + RunTypeAutoBuild RunType = "AutoBuild" + RunTypeAutoRun RunType = "AutoRun" + RunTypeQuickBuild RunType = "QuickBuild" + RunTypeQuickRun RunType = "QuickRun" +) + +// PossibleRunTypeValues returns the possible values for the RunType const type. +func PossibleRunTypeValues() []RunType { + return []RunType{ + RunTypeAutoBuild, + RunTypeAutoRun, + RunTypeQuickBuild, + RunTypeQuickRun, + } +} + +// SKUName - The SKU name of the container registry. Required for registry creation. +type SKUName string + +const ( + SKUNameBasic SKUName = "Basic" + SKUNameClassic SKUName = "Classic" + SKUNamePremium SKUName = "Premium" + SKUNameStandard SKUName = "Standard" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNameBasic, + SKUNameClassic, + SKUNamePremium, + SKUNameStandard, + } +} + +// SKUTier - The SKU tier based on the SKU name. +type SKUTier string + +const ( + SKUTierBasic SKUTier = "Basic" + SKUTierClassic SKUTier = "Classic" + SKUTierPremium SKUTier = "Premium" + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierClassic, + SKUTierPremium, + SKUTierStandard, + } +} + +// SecretObjectType - The type of the secret object which determines how the value of the secret object has to be interpreted. +type SecretObjectType string + +const ( + SecretObjectTypeOpaque SecretObjectType = "Opaque" + SecretObjectTypeVaultsecret SecretObjectType = "Vaultsecret" +) + +// PossibleSecretObjectTypeValues returns the possible values for the SecretObjectType const type. +func PossibleSecretObjectTypeValues() []SecretObjectType { + return []SecretObjectType{ + SecretObjectTypeOpaque, + SecretObjectTypeVaultsecret, + } +} + +// SourceControlType - The type of source control service. +type SourceControlType string + +const ( + SourceControlTypeGithub SourceControlType = "Github" + SourceControlTypeVisualStudioTeamService SourceControlType = "VisualStudioTeamService" +) + +// PossibleSourceControlTypeValues returns the possible values for the SourceControlType const type. +func PossibleSourceControlTypeValues() []SourceControlType { + return []SourceControlType{ + SourceControlTypeGithub, + SourceControlTypeVisualStudioTeamService, + } +} + +// SourceRegistryLoginMode - The authentication mode which determines the source registry login scope. The credentials for +// the source registry will be generated using the given scope. These credentials will be used to login to +// the source registry during the run. +type SourceRegistryLoginMode string + +const ( + SourceRegistryLoginModeDefault SourceRegistryLoginMode = "Default" + SourceRegistryLoginModeNone SourceRegistryLoginMode = "None" +) + +// PossibleSourceRegistryLoginModeValues returns the possible values for the SourceRegistryLoginMode const type. +func PossibleSourceRegistryLoginModeValues() []SourceRegistryLoginMode { + return []SourceRegistryLoginMode{ + SourceRegistryLoginModeDefault, + SourceRegistryLoginModeNone, + } +} + +type SourceTriggerEvent string + +const ( + SourceTriggerEventCommit SourceTriggerEvent = "commit" + SourceTriggerEventPullrequest SourceTriggerEvent = "pullrequest" +) + +// PossibleSourceTriggerEventValues returns the possible values for the SourceTriggerEvent const type. +func PossibleSourceTriggerEventValues() []SourceTriggerEvent { + return []SourceTriggerEvent{ + SourceTriggerEventCommit, + SourceTriggerEventPullrequest, + } +} + +// StepType - The type of the step. +type StepType string + +const ( + StepTypeDocker StepType = "Docker" + StepTypeEncodedTask StepType = "EncodedTask" + StepTypeFileTask StepType = "FileTask" +) + +// PossibleStepTypeValues returns the possible values for the StepType const type. +func PossibleStepTypeValues() []StepType { + return []StepType{ + StepTypeDocker, + StepTypeEncodedTask, + StepTypeFileTask, + } +} + +// TaskStatus - The current status of task. +type TaskStatus string + +const ( + TaskStatusDisabled TaskStatus = "Disabled" + TaskStatusEnabled TaskStatus = "Enabled" +) + +// PossibleTaskStatusValues returns the possible values for the TaskStatus const type. +func PossibleTaskStatusValues() []TaskStatus { + return []TaskStatus{ + TaskStatusDisabled, + TaskStatusEnabled, + } +} + +type TokenCertificateName string + +const ( + TokenCertificateNameCertificate1 TokenCertificateName = "certificate1" + TokenCertificateNameCertificate2 TokenCertificateName = "certificate2" +) + +// PossibleTokenCertificateNameValues returns the possible values for the TokenCertificateName const type. +func PossibleTokenCertificateNameValues() []TokenCertificateName { + return []TokenCertificateName{ + TokenCertificateNameCertificate1, + TokenCertificateNameCertificate2, + } +} + +// TokenPasswordName - The password name "password1" or "password2" +type TokenPasswordName string + +const ( + TokenPasswordNamePassword1 TokenPasswordName = "password1" + TokenPasswordNamePassword2 TokenPasswordName = "password2" +) + +// PossibleTokenPasswordNameValues returns the possible values for the TokenPasswordName const type. +func PossibleTokenPasswordNameValues() []TokenPasswordName { + return []TokenPasswordName{ + TokenPasswordNamePassword1, + TokenPasswordNamePassword2, + } +} + +// TokenStatus - The status of the token example enabled or disabled. +type TokenStatus string + +const ( + TokenStatusDisabled TokenStatus = "disabled" + TokenStatusEnabled TokenStatus = "enabled" +) + +// PossibleTokenStatusValues returns the possible values for the TokenStatus const type. +func PossibleTokenStatusValues() []TokenStatus { + return []TokenStatus{ + TokenStatusDisabled, + TokenStatusEnabled, + } +} + +// TokenType - The type of Auth token. +type TokenType string + +const ( + TokenTypeOAuth TokenType = "OAuth" + TokenTypePAT TokenType = "PAT" +) + +// PossibleTokenTypeValues returns the possible values for the TokenType const type. +func PossibleTokenTypeValues() []TokenType { + return []TokenType{ + TokenTypeOAuth, + TokenTypePAT, + } +} + +// TriggerStatus - The current status of trigger. +type TriggerStatus string + +const ( + TriggerStatusDisabled TriggerStatus = "Disabled" + TriggerStatusEnabled TriggerStatus = "Enabled" +) + +// PossibleTriggerStatusValues returns the possible values for the TriggerStatus const type. +func PossibleTriggerStatusValues() []TriggerStatus { + return []TriggerStatus{ + TriggerStatusDisabled, + TriggerStatusEnabled, + } +} + +// TrustPolicyType - The type of trust policy. +type TrustPolicyType string + +const ( + TrustPolicyTypeNotary TrustPolicyType = "Notary" +) + +// PossibleTrustPolicyTypeValues returns the possible values for the TrustPolicyType const type. +func PossibleTrustPolicyTypeValues() []TrustPolicyType { + return []TrustPolicyType{ + TrustPolicyTypeNotary, + } +} + +// UpdateTriggerPayloadType - Type of Payload body for Base image update triggers. +type UpdateTriggerPayloadType string + +const ( + UpdateTriggerPayloadTypeDefault UpdateTriggerPayloadType = "Default" + UpdateTriggerPayloadTypeToken UpdateTriggerPayloadType = "Token" +) + +// PossibleUpdateTriggerPayloadTypeValues returns the possible values for the UpdateTriggerPayloadType const type. +func PossibleUpdateTriggerPayloadTypeValues() []UpdateTriggerPayloadType { + return []UpdateTriggerPayloadType{ + UpdateTriggerPayloadTypeDefault, + UpdateTriggerPayloadTypeToken, + } +} + +// Variant - Variant of the CPU. +type Variant string + +const ( + VariantV6 Variant = "v6" + VariantV7 Variant = "v7" + VariantV8 Variant = "v8" +) + +// PossibleVariantValues returns the possible values for the Variant const type. +func PossibleVariantValues() []Variant { + return []Variant{ + VariantV6, + VariantV7, + VariantV8, + } +} + +type WebhookAction string + +const ( + WebhookActionChartDelete WebhookAction = "chart_delete" + WebhookActionChartPush WebhookAction = "chart_push" + WebhookActionDelete WebhookAction = "delete" + WebhookActionPush WebhookAction = "push" + WebhookActionQuarantine WebhookAction = "quarantine" +) + +// PossibleWebhookActionValues returns the possible values for the WebhookAction const type. +func PossibleWebhookActionValues() []WebhookAction { + return []WebhookAction{ + WebhookActionChartDelete, + WebhookActionChartPush, + WebhookActionDelete, + WebhookActionPush, + WebhookActionQuarantine, + } +} + +// WebhookStatus - The status of the webhook at the time the operation was called. +type WebhookStatus string + +const ( + WebhookStatusDisabled WebhookStatus = "disabled" + WebhookStatusEnabled WebhookStatus = "enabled" +) + +// PossibleWebhookStatusValues returns the possible values for the WebhookStatus const type. +func PossibleWebhookStatusValues() []WebhookStatus { + return []WebhookStatus{ + WebhookStatusDisabled, + WebhookStatusEnabled, + } +} + +// ZoneRedundancy - Whether or not zone redundancy is enabled for this container registry +type ZoneRedundancy string + +const ( + ZoneRedundancyDisabled ZoneRedundancy = "Disabled" + ZoneRedundancyEnabled ZoneRedundancy = "Enabled" +) + +// PossibleZoneRedundancyValues returns the possible values for the ZoneRedundancy const type. +func PossibleZoneRedundancyValues() []ZoneRedundancy { + return []ZoneRedundancy{ + ZoneRedundancyDisabled, + ZoneRedundancyEnabled, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/credentialsets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/credentialsets_client.go new file mode 100644 index 0000000000..b900f870d8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/credentialsets_client.go @@ -0,0 +1,431 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CredentialSetsClient contains the methods for the CredentialSets group. +// Don't use this type directly, use NewCredentialSetsClient() instead. +type CredentialSetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCredentialSetsClient creates a new instance of CredentialSetsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewCredentialSetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CredentialSetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CredentialSetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a credential set for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - credentialSetName - The name of the credential set. +// - credentialSetCreateParameters - The parameters for creating a credential set. +// - options - CredentialSetsClientBeginCreateOptions contains the optional parameters for the CredentialSetsClient.BeginCreate +// method. +func (client *CredentialSetsClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, credentialSetCreateParameters CredentialSet, options *CredentialSetsClientBeginCreateOptions) (*runtime.Poller[CredentialSetsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, credentialSetName, credentialSetCreateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CredentialSetsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CredentialSetsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a credential set for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *CredentialSetsClient) create(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, credentialSetCreateParameters CredentialSet, options *CredentialSetsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "CredentialSetsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, credentialSetName, credentialSetCreateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *CredentialSetsClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, credentialSetCreateParameters CredentialSet, options *CredentialSetsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/credentialSets/{credentialSetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if credentialSetName == "" { + return nil, errors.New("parameter credentialSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{credentialSetName}", url.PathEscape(credentialSetName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, credentialSetCreateParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a credential set from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - credentialSetName - The name of the credential set. +// - options - CredentialSetsClientBeginDeleteOptions contains the optional parameters for the CredentialSetsClient.BeginDelete +// method. +func (client *CredentialSetsClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, options *CredentialSetsClientBeginDeleteOptions) (*runtime.Poller[CredentialSetsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, credentialSetName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CredentialSetsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CredentialSetsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a credential set from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *CredentialSetsClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, options *CredentialSetsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CredentialSetsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, credentialSetName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CredentialSetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, options *CredentialSetsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/credentialSets/{credentialSetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if credentialSetName == "" { + return nil, errors.New("parameter credentialSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{credentialSetName}", url.PathEscape(credentialSetName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the properties of the specified credential set resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - credentialSetName - The name of the credential set. +// - options - CredentialSetsClientGetOptions contains the optional parameters for the CredentialSetsClient.Get method. +func (client *CredentialSetsClient) Get(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, options *CredentialSetsClientGetOptions) (CredentialSetsClientGetResponse, error) { + var err error + const operationName = "CredentialSetsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, credentialSetName, options) + if err != nil { + return CredentialSetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CredentialSetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CredentialSetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CredentialSetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, options *CredentialSetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/credentialSets/{credentialSetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if credentialSetName == "" { + return nil, errors.New("parameter credentialSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{credentialSetName}", url.PathEscape(credentialSetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CredentialSetsClient) getHandleResponse(resp *http.Response) (CredentialSetsClientGetResponse, error) { + result := CredentialSetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CredentialSet); err != nil { + return CredentialSetsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all credential set resources for the specified container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - CredentialSetsClientListOptions contains the optional parameters for the CredentialSetsClient.NewListPager method. +func (client *CredentialSetsClient) NewListPager(resourceGroupName string, registryName string, options *CredentialSetsClientListOptions) *runtime.Pager[CredentialSetsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CredentialSetsClientListResponse]{ + More: func(page CredentialSetsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CredentialSetsClientListResponse) (CredentialSetsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CredentialSetsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return CredentialSetsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CredentialSetsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *CredentialSetsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/credentialSets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CredentialSetsClient) listHandleResponse(resp *http.Response) (CredentialSetsClientListResponse, error) { + result := CredentialSetsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CredentialSetListResult); err != nil { + return CredentialSetsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a credential set for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - credentialSetName - The name of the credential set. +// - credentialSetUpdateParameters - The parameters for updating a credential set. +// - options - CredentialSetsClientBeginUpdateOptions contains the optional parameters for the CredentialSetsClient.BeginUpdate +// method. +func (client *CredentialSetsClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, credentialSetUpdateParameters CredentialSetUpdateParameters, options *CredentialSetsClientBeginUpdateOptions) (*runtime.Poller[CredentialSetsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, credentialSetName, credentialSetUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CredentialSetsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CredentialSetsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a credential set for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *CredentialSetsClient) update(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, credentialSetUpdateParameters CredentialSetUpdateParameters, options *CredentialSetsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CredentialSetsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, credentialSetName, credentialSetUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CredentialSetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, credentialSetName string, credentialSetUpdateParameters CredentialSetUpdateParameters, options *CredentialSetsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/credentialSets/{credentialSetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if credentialSetName == "" { + return nil, errors.New("parameter credentialSetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{credentialSetName}", url.PathEscape(credentialSetName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, credentialSetUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/interfaces.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/interfaces.go new file mode 100644 index 0000000000..d1dddecae4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/interfaces.go @@ -0,0 +1,36 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +// RunRequestClassification provides polymorphic access to related types. +// Call the interface's GetRunRequest() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DockerBuildRequest, *EncodedTaskRunRequest, *FileTaskRunRequest, *RunRequest, *TaskRunRequest +type RunRequestClassification interface { + // GetRunRequest returns the RunRequest content of the underlying type. + GetRunRequest() *RunRequest +} + +// TaskStepPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetTaskStepProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DockerBuildStep, *EncodedTaskStep, *FileTaskStep, *TaskStepProperties +type TaskStepPropertiesClassification interface { + // GetTaskStepProperties returns the TaskStepProperties content of the underlying type. + GetTaskStepProperties() *TaskStepProperties +} + +// TaskStepUpdateParametersClassification provides polymorphic access to related types. +// Call the interface's GetTaskStepUpdateParameters() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DockerBuildStepUpdateParameters, *EncodedTaskStepUpdateParameters, *FileTaskStepUpdateParameters, *TaskStepUpdateParameters +type TaskStepUpdateParametersClassification interface { + // GetTaskStepUpdateParameters returns the TaskStepUpdateParameters content of the underlying type. + GetTaskStepUpdateParameters() *TaskStepUpdateParameters +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models.go new file mode 100644 index 0000000000..f5c28b280a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models.go @@ -0,0 +1,2495 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import "time" + +// Actor - The agent that initiated the event. For most situations, this could be from the authorization context of the request. +type Actor struct { + // The subject or username associated with the request context that generated the event. + Name *string +} + +// AgentPool - The agentpool that has the ARM resource and properties. The agentpool will have all information to create an +// agent pool. +type AgentPool struct { + // REQUIRED; The location of the resource. This cannot be changed after the resource is created. + Location *string + + // The properties associated with the agent pool + Properties *AgentPoolProperties + + // The tags of the resource. + Tags map[string]*string + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// AgentPoolListResult - The collection of agent pools. +type AgentPoolListResult struct { + // The URI that can be used to request the next set of paged results. + NextLink *string + + // The collection value. + Value []*AgentPool +} + +// AgentPoolProperties - The properties of agent pool. +type AgentPoolProperties struct { + // The count of agent machine + Count *int32 + + // The OS of agent machine + OS *OS + + // The Tier of agent machine + Tier *string + + // The Virtual Network Subnet Resource Id of the agent machine + VirtualNetworkSubnetResourceID *string + + // READ-ONLY; The provisioning state of this agent pool + ProvisioningState *ProvisioningState +} + +type AgentPoolPropertiesUpdateParameters struct { + // The count of agent machine + Count *int32 +} + +// AgentPoolQueueStatus - The QueueStatus of Agent Pool +type AgentPoolQueueStatus struct { + // The number of pending runs in the queue + Count *int32 +} + +// AgentPoolUpdateParameters - The parameters for updating an agent pool. +type AgentPoolUpdateParameters struct { + // The properties associated with the agent pool + Properties *AgentPoolPropertiesUpdateParameters + + // The ARM resource tags. + Tags map[string]*string +} + +// AgentProperties - The properties that determine the run agent configuration. +type AgentProperties struct { + // The CPU configuration in terms of number of cores required for the run. + CPU *int32 +} + +// Argument - The properties of a run argument. +type Argument struct { + // REQUIRED; The name of the argument. + Name *string + + // REQUIRED; The value of the argument. + Value *string + + // Flag to indicate whether the argument represents a secret and want to be removed from build logs. + IsSecret *bool +} + +// AuthCredential - Authentication credential stored for an upstream. +type AuthCredential struct { + // The name of the credential. + Name *CredentialName + + // KeyVault Secret URI for accessing the password. + PasswordSecretIdentifier *string + + // KeyVault Secret URI for accessing the username. + UsernameSecretIdentifier *string + + // READ-ONLY; This provides data pertaining to the health of the auth credential. + CredentialHealth *CredentialHealth +} + +// AuthInfo - The authorization properties for accessing the source code repository. +type AuthInfo struct { + // REQUIRED; The access token used to access the source control provider. + Token *string + + // REQUIRED; The type of Auth token. + TokenType *TokenType + + // Time in seconds that the token remains valid + ExpiresIn *int32 + + // The refresh token used to refresh the access token. + RefreshToken *string + + // The scope of the access token. + Scope *string +} + +// AuthInfoUpdateParameters - The authorization properties for accessing the source code repository. +type AuthInfoUpdateParameters struct { + // Time in seconds that the token remains valid + ExpiresIn *int32 + + // The refresh token used to refresh the access token. + RefreshToken *string + + // The scope of the access token. + Scope *string + + // The access token used to access the source control provider. + Token *string + + // The type of Auth token. + TokenType *TokenType +} + +// BaseImageDependency - Properties that describe a base image dependency. +type BaseImageDependency struct { + // The sha256-based digest of the image manifest. + Digest *string + + // The registry login server. + Registry *string + + // The repository name. + Repository *string + + // The tag name. + Tag *string + + // The type of the base image dependency. + Type *BaseImageDependencyType +} + +// BaseImageTrigger - The trigger based on base image dependency. +type BaseImageTrigger struct { + // REQUIRED; The type of the auto trigger for base image dependency updates. + BaseImageTriggerType *BaseImageTriggerType + + // REQUIRED; The name of the trigger. + Name *string + + // The current status of trigger. + Status *TriggerStatus + + // The endpoint URL for receiving update triggers. + UpdateTriggerEndpoint *string + + // Type of Payload body for Base image update triggers. + UpdateTriggerPayloadType *UpdateTriggerPayloadType +} + +// BaseImageTriggerUpdateParameters - The properties for updating base image dependency trigger. +type BaseImageTriggerUpdateParameters struct { + // REQUIRED; The name of the trigger. + Name *string + + // The type of the auto trigger for base image dependency updates. + BaseImageTriggerType *BaseImageTriggerType + + // The current status of trigger. + Status *TriggerStatus + + // The endpoint URL for receiving update triggers. + UpdateTriggerEndpoint *string + + // Type of Payload body for Base image update triggers. + UpdateTriggerPayloadType *UpdateTriggerPayloadType +} + +// CacheRule - An object that represents a cache rule for a container registry. +type CacheRule struct { + // The properties of the cache rule. + Properties *CacheRuleProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// CacheRuleProperties - The properties of a cache rule. +type CacheRuleProperties struct { + // The ARM resource ID of the credential store which is associated with the cache rule. + CredentialSetResourceID *string + + // Source repository pulled from upstream. + SourceRepository *string + + // Target repository specified in docker pull command. Eg: docker pull myregistry.azurecr.io/{targetRepository}:{tag} + TargetRepository *string + + // READ-ONLY; The creation date of the cache rule. + CreationDate *time.Time + + // READ-ONLY; Provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// CacheRuleUpdateParameters - The parameters for updating a cache rule. +type CacheRuleUpdateParameters struct { + // The properties of the cache rule update parameters. + Properties *CacheRuleUpdateProperties +} + +// CacheRuleUpdateProperties - The parameters for updating cache rule properties. +type CacheRuleUpdateProperties struct { + // The ARM resource ID of the credential store which is associated with the Cache rule. + CredentialSetResourceID *string +} + +// CacheRulesListResult - The result of a request to list cache rules for a container registry. +type CacheRulesListResult struct { + // If provided, client must use NextLink URI to request next list of cache rules. + NextLink *string + + // The list of cache rules. + Value []*CacheRule +} + +// CallbackConfig - The configuration of service URI and custom headers for the webhook. +type CallbackConfig struct { + // REQUIRED; The service URI for the webhook to post notifications. + ServiceURI *string + + // Custom headers that will be added to the webhook notifications. + CustomHeaders map[string]*string +} + +// CredentialHealth - The health of the auth credential. +type CredentialHealth struct { + // Error code representing the health check error. + ErrorCode *string + + // Descriptive message representing the health check error. + ErrorMessage *string + + // The health status of credential. + Status *CredentialHealthStatus +} + +// CredentialSet - An object that represents a credential set resource for a container registry. +type CredentialSet struct { + // Identities associated with the resource. This is used to access the KeyVault secrets. + Identity *IdentityProperties + + // The properties of the credential set. + Properties *CredentialSetProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// CredentialSetListResult - The result of a request to list credential sets for a container registry. +type CredentialSetListResult struct { + // The URI that can be used to request the next list of credential sets. + NextLink *string + + // The list of credential sets. Since this list may be incomplete, the nextLink field should be used to request the next list + // of credential sets. + Value []*CredentialSet +} + +// CredentialSetProperties - The properties of a credential set resource. +type CredentialSetProperties struct { + // List of authentication credentials stored for an upstream. Usually consists of a primary and an optional secondary credential. + AuthCredentials []*AuthCredential + + // The credentials are stored for this upstream or login server. + LoginServer *string + + // READ-ONLY; The creation date of credential store resource. + CreationDate *time.Time + + // READ-ONLY; Provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// CredentialSetUpdateParameters - The parameters for updating a credential set +type CredentialSetUpdateParameters struct { + // Identities associated with the resource. This is used to access the KeyVault secrets. + Identity *IdentityProperties + + // The properties of the credential set update parameters + Properties *CredentialSetUpdateProperties +} + +// CredentialSetUpdateProperties - The parameters for updating credential set properties. +type CredentialSetUpdateProperties struct { + // List of authentication credentials stored for an upstream. Usually consists of a primary and an optional secondary credential. + AuthCredentials []*AuthCredential +} + +// Credentials - The parameters that describes a set of credentials that will be used when a run is invoked. +type Credentials struct { + // Describes the credential parameters for accessing other custom registries. The key for the dictionary item will be the + // registry login server (myregistry.azurecr.io) and the value of the item will be + // the registry credentials for accessing the registry. + CustomRegistries map[string]*CustomRegistryCredentials + + // Describes the credential parameters for accessing the source registry. + SourceRegistry *SourceRegistryCredentials +} + +// CustomRegistryCredentials - Describes the credentials that will be used to access a custom registry during a run. +type CustomRegistryCredentials struct { + // Indicates the managed identity assigned to the custom credential. If a user-assigned identity this value is the Client + // ID. If a system-assigned identity, the value will be system. In the case of a + // system-assigned identity, the Client ID will be determined by the runner. This identity may be used to authenticate to + // key vault to retrieve credentials or it may be the only source of authentication + // used for accessing the registry. + Identity *string + + // The password for logging into the custom registry. The password is a secret object that allows multiple ways of providing + // the value for it. + Password *SecretObject + + // The username for logging into the custom registry. + UserName *SecretObject +} + +// DockerBuildRequest - The parameters for a docker quick build. +type DockerBuildRequest struct { + // REQUIRED; The Docker file path relative to the source location. + DockerFilePath *string + + // REQUIRED; The platform properties against which the run has to happen. + Platform *PlatformProperties + + // REQUIRED; The type of the run request. + Type *string + + // The machine configuration of the run agent. + AgentConfiguration *AgentProperties + + // The dedicated agent pool for the run. + AgentPoolName *string + + // The collection of override arguments to be used when executing the run. + Arguments []*Argument + + // The properties that describes a set of credentials that will be used when this run is invoked. + Credentials *Credentials + + // The fully qualified image names including the repository and tag. + ImageNames []*string + + // The value that indicates whether archiving is enabled for the run or not. + IsArchiveEnabled *bool + + // The value of this property indicates whether the image built should be pushed to the registry or not. + IsPushEnabled *bool + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string + + // The value of this property indicates whether the image cache is enabled or not. + NoCache *bool + + // The URL(absolute or relative) of the source context. It can be an URL to a tar or git repository. If it is relative URL, + // the relative path should be obtained from calling listBuildSourceUploadUrl API. + SourceLocation *string + + // The name of the target build stage for the docker build. + Target *string + + // Run timeout in seconds. + Timeout *int32 +} + +// GetRunRequest implements the RunRequestClassification interface for type DockerBuildRequest. +func (d *DockerBuildRequest) GetRunRequest() *RunRequest { + return &RunRequest{ + AgentPoolName: d.AgentPoolName, + IsArchiveEnabled: d.IsArchiveEnabled, + LogTemplate: d.LogTemplate, + Type: d.Type, + } +} + +// DockerBuildStep - The Docker build step. +type DockerBuildStep struct { + // REQUIRED; The Docker file path relative to the source context. + DockerFilePath *string + + // REQUIRED; The type of the step. + Type *StepType + + // The collection of override arguments to be used when executing this build step. + Arguments []*Argument + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // The fully qualified image names including the repository and tag. + ImageNames []*string + + // The value of this property indicates whether the image built should be pushed to the registry or not. + IsPushEnabled *bool + + // The value of this property indicates whether the image cache is enabled or not. + NoCache *bool + + // The name of the target build stage for the docker build. + Target *string + + // READ-ONLY; List of base image dependencies for a step. + BaseImageDependencies []*BaseImageDependency +} + +// GetTaskStepProperties implements the TaskStepPropertiesClassification interface for type DockerBuildStep. +func (d *DockerBuildStep) GetTaskStepProperties() *TaskStepProperties { + return &TaskStepProperties{ + BaseImageDependencies: d.BaseImageDependencies, + ContextAccessToken: d.ContextAccessToken, + ContextPath: d.ContextPath, + Type: d.Type, + } +} + +// DockerBuildStepUpdateParameters - The properties for updating a docker build step. +type DockerBuildStepUpdateParameters struct { + // REQUIRED; The type of the step. + Type *StepType + + // The collection of override arguments to be used when executing this build step. + Arguments []*Argument + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // The Docker file path relative to the source context. + DockerFilePath *string + + // The fully qualified image names including the repository and tag. + ImageNames []*string + + // The value of this property indicates whether the image built should be pushed to the registry or not. + IsPushEnabled *bool + + // The value of this property indicates whether the image cache is enabled or not. + NoCache *bool + + // The name of the target build stage for the docker build. + Target *string +} + +// GetTaskStepUpdateParameters implements the TaskStepUpdateParametersClassification interface for type DockerBuildStepUpdateParameters. +func (d *DockerBuildStepUpdateParameters) GetTaskStepUpdateParameters() *TaskStepUpdateParameters { + return &TaskStepUpdateParameters{ + ContextAccessToken: d.ContextAccessToken, + ContextPath: d.ContextPath, + Type: d.Type, + } +} + +// EncodedTaskRunRequest - The parameters for a quick task run request. +type EncodedTaskRunRequest struct { + // REQUIRED; Base64 encoded value of the template/definition file content. + EncodedTaskContent *string + + // REQUIRED; The platform properties against which the run has to happen. + Platform *PlatformProperties + + // REQUIRED; The type of the run request. + Type *string + + // The machine configuration of the run agent. + AgentConfiguration *AgentProperties + + // The dedicated agent pool for the run. + AgentPoolName *string + + // The properties that describes a set of credentials that will be used when this run is invoked. + Credentials *Credentials + + // Base64 encoded value of the parameters/values file content. + EncodedValuesContent *string + + // The value that indicates whether archiving is enabled for the run or not. + IsArchiveEnabled *bool + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string + + // The URL(absolute or relative) of the source context. It can be an URL to a tar or git repository. If it is relative URL, + // the relative path should be obtained from calling listBuildSourceUploadUrl API. + SourceLocation *string + + // Run timeout in seconds. + Timeout *int32 + + // The collection of overridable values that can be passed when running a task. + Values []*SetValue +} + +// GetRunRequest implements the RunRequestClassification interface for type EncodedTaskRunRequest. +func (e *EncodedTaskRunRequest) GetRunRequest() *RunRequest { + return &RunRequest{ + AgentPoolName: e.AgentPoolName, + IsArchiveEnabled: e.IsArchiveEnabled, + LogTemplate: e.LogTemplate, + Type: e.Type, + } +} + +// EncodedTaskStep - The properties of a encoded task step. +type EncodedTaskStep struct { + // REQUIRED; Base64 encoded value of the template/definition file content. + EncodedTaskContent *string + + // REQUIRED; The type of the step. + Type *StepType + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // Base64 encoded value of the parameters/values file content. + EncodedValuesContent *string + + // The collection of overridable values that can be passed when running a task. + Values []*SetValue + + // READ-ONLY; List of base image dependencies for a step. + BaseImageDependencies []*BaseImageDependency +} + +// GetTaskStepProperties implements the TaskStepPropertiesClassification interface for type EncodedTaskStep. +func (e *EncodedTaskStep) GetTaskStepProperties() *TaskStepProperties { + return &TaskStepProperties{ + BaseImageDependencies: e.BaseImageDependencies, + ContextAccessToken: e.ContextAccessToken, + ContextPath: e.ContextPath, + Type: e.Type, + } +} + +// EncodedTaskStepUpdateParameters - The properties for updating encoded task step. +type EncodedTaskStepUpdateParameters struct { + // REQUIRED; The type of the step. + Type *StepType + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // Base64 encoded value of the template/definition file content. + EncodedTaskContent *string + + // Base64 encoded value of the parameters/values file content. + EncodedValuesContent *string + + // The collection of overridable values that can be passed when running a task. + Values []*SetValue +} + +// GetTaskStepUpdateParameters implements the TaskStepUpdateParametersClassification interface for type EncodedTaskStepUpdateParameters. +func (e *EncodedTaskStepUpdateParameters) GetTaskStepUpdateParameters() *TaskStepUpdateParameters { + return &TaskStepUpdateParameters{ + ContextAccessToken: e.ContextAccessToken, + ContextPath: e.ContextPath, + Type: e.Type, + } +} + +type EncryptionProperty struct { + // Key vault properties. + KeyVaultProperties *KeyVaultProperties + + // Indicates whether or not the encryption is enabled for container registry. + Status *EncryptionStatus +} + +// Event - The event for a webhook. +type Event struct { + // The event request message sent to the service URI. + EventRequestMessage *EventRequestMessage + + // The event response message received from the service URI. + EventResponseMessage *EventResponseMessage + + // The event ID. + ID *string +} + +// EventContent - The content of the event request message. +type EventContent struct { + // The action that encompasses the provided event. + Action *string + + // The agent that initiated the event. For most situations, this could be from the authorization context of the request. + Actor *Actor + + // The event ID. + ID *string + + // The request that generated the event. + Request *Request + + // The registry node that generated the event. Put differently, while the actor initiates the event, the source generates + // it. + Source *Source + + // The target of the event. + Target *Target + + // The time at which the event occurred. + Timestamp *time.Time +} + +// EventInfo - The basic information of an event. +type EventInfo struct { + // The event ID. + ID *string +} + +// EventListResult - The result of a request to list events for a webhook. +type EventListResult struct { + // The URI that can be used to request the next list of events. + NextLink *string + + // The list of events. Since this list may be incomplete, the nextLink field should be used to request the next list of events. + Value []*Event +} + +// EventRequestMessage - The event request message sent to the service URI. +type EventRequestMessage struct { + // The content of the event request message. + Content *EventContent + + // The headers of the event request message. + Headers map[string]*string + + // The HTTP method used to send the event request message. + Method *string + + // The URI used to send the event request message. + RequestURI *string + + // The HTTP message version. + Version *string +} + +// EventResponseMessage - The event response message received from the service URI. +type EventResponseMessage struct { + // The content of the event response message. + Content *string + + // The headers of the event response message. + Headers map[string]*string + + // The reason phrase of the event response message. + ReasonPhrase *string + + // The status code of the event response message. + StatusCode *string + + // The HTTP message version. + Version *string +} + +// ExportPolicy - The export policy for a container registry. +type ExportPolicy struct { + // The value that indicates whether the policy is enabled or not. + Status *ExportPolicyStatus +} + +// FileTaskRunRequest - The request parameters for a scheduling run against a task file. +type FileTaskRunRequest struct { + // REQUIRED; The platform properties against which the run has to happen. + Platform *PlatformProperties + + // REQUIRED; The template/definition file path relative to the source. + TaskFilePath *string + + // REQUIRED; The type of the run request. + Type *string + + // The machine configuration of the run agent. + AgentConfiguration *AgentProperties + + // The dedicated agent pool for the run. + AgentPoolName *string + + // The properties that describes a set of credentials that will be used when this run is invoked. + Credentials *Credentials + + // The value that indicates whether archiving is enabled for the run or not. + IsArchiveEnabled *bool + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string + + // The URL(absolute or relative) of the source context. It can be an URL to a tar or git repository. If it is relative URL, + // the relative path should be obtained from calling listBuildSourceUploadUrl API. + SourceLocation *string + + // Run timeout in seconds. + Timeout *int32 + + // The collection of overridable values that can be passed when running a task. + Values []*SetValue + + // The values/parameters file path relative to the source. + ValuesFilePath *string +} + +// GetRunRequest implements the RunRequestClassification interface for type FileTaskRunRequest. +func (f *FileTaskRunRequest) GetRunRequest() *RunRequest { + return &RunRequest{ + AgentPoolName: f.AgentPoolName, + IsArchiveEnabled: f.IsArchiveEnabled, + LogTemplate: f.LogTemplate, + Type: f.Type, + } +} + +// FileTaskStep - The properties of a task step. +type FileTaskStep struct { + // REQUIRED; The task template/definition file path relative to the source context. + TaskFilePath *string + + // REQUIRED; The type of the step. + Type *StepType + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // The collection of overridable values that can be passed when running a task. + Values []*SetValue + + // The task values/parameters file path relative to the source context. + ValuesFilePath *string + + // READ-ONLY; List of base image dependencies for a step. + BaseImageDependencies []*BaseImageDependency +} + +// GetTaskStepProperties implements the TaskStepPropertiesClassification interface for type FileTaskStep. +func (f *FileTaskStep) GetTaskStepProperties() *TaskStepProperties { + return &TaskStepProperties{ + BaseImageDependencies: f.BaseImageDependencies, + ContextAccessToken: f.ContextAccessToken, + ContextPath: f.ContextPath, + Type: f.Type, + } +} + +// FileTaskStepUpdateParameters - The properties of updating a task step. +type FileTaskStepUpdateParameters struct { + // REQUIRED; The type of the step. + Type *StepType + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // The task template/definition file path relative to the source context. + TaskFilePath *string + + // The collection of overridable values that can be passed when running a task. + Values []*SetValue + + // The values/parameters file path relative to the source context. + ValuesFilePath *string +} + +// GetTaskStepUpdateParameters implements the TaskStepUpdateParametersClassification interface for type FileTaskStepUpdateParameters. +func (f *FileTaskStepUpdateParameters) GetTaskStepUpdateParameters() *TaskStepUpdateParameters { + return &TaskStepUpdateParameters{ + ContextAccessToken: f.ContextAccessToken, + ContextPath: f.ContextPath, + Type: f.Type, + } +} + +// GenerateCredentialsParameters - The parameters used to generate credentials for a specified token or user of a container +// registry. +type GenerateCredentialsParameters struct { + // The expiry date of the generated credentials after which the credentials become invalid. + Expiry *time.Time + + // Specifies name of the password which should be regenerated if any -- password1 or password2. + Name *TokenPasswordName + + // The resource ID of the token for which credentials have to be generated. + TokenID *string +} + +// GenerateCredentialsResult - The response from the GenerateCredentials operation. +type GenerateCredentialsResult struct { + // The list of passwords for a container registry. + Passwords []*TokenPassword + + // The username for a container registry. + Username *string +} + +// IPRule - IP rule with specific IP or IP range in CIDR format. +type IPRule struct { + // REQUIRED; Specifies the IP or IP range in CIDR format. Only IPV4 address is allowed. + IPAddressOrRange *string + + // The action of IP ACL rule. + Action *Action +} + +// IdentityProperties - Managed identity for the resource. +type IdentityProperties struct { + // The identity type. + Type *ResourceIdentityType + + // The list of user identities associated with the 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]*UserIdentityProperties + + // READ-ONLY; The principal ID of resource identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of resource. + TenantID *string +} + +// ImageDescriptor - Properties for a registry image. +type ImageDescriptor struct { + // The sha256-based digest of the image manifest. + Digest *string + + // The registry login server. + Registry *string + + // The repository name. + Repository *string + + // The tag name. + Tag *string +} + +// ImageUpdateTrigger - The image update trigger that caused a build. +type ImageUpdateTrigger struct { + // The unique ID of the trigger. + ID *string + + // The list of image updates that caused the build. + Images []*ImageDescriptor + + // The timestamp when the image update happened. + Timestamp *time.Time +} + +type ImportImageParameters struct { + // REQUIRED; The source of the image. + Source *ImportSource + + // When Force, any existing target tags will be overwritten. When NoForce, any existing target tags will fail the operation + // before any copying begins. + Mode *ImportMode + + // List of strings of the form repo[:tag]. When tag is omitted the source will be used (or 'latest' if source tag is also + // omitted). + TargetTags []*string + + // List of strings of repository names to do a manifest only copy. No tag will be created. + UntaggedTargetRepositories []*string +} + +type ImportSource struct { + // REQUIRED; Repository name of the source image. Specify an image by repository ('hello-world'). This will use the 'latest' + // tag. Specify an image by tag ('hello-world:latest'). Specify an image by sha256-based + // manifest digest ('hello-world@sha256:abc123'). + SourceImage *string + + // Credentials used when importing from a registry uri. + Credentials *ImportSourceCredentials + + // The address of the source registry (e.g. 'mcr.microsoft.com'). + RegistryURI *string + + // The resource identifier of the source Azure Container Registry. + ResourceID *string +} + +type ImportSourceCredentials struct { + // REQUIRED; The password used to authenticate with the source registry. + Password *string + + // The username to authenticate with the source registry. + Username *string +} + +type KeyVaultProperties struct { + // The client id of the identity which will be used to access key vault. + Identity *string + + // Key vault uri to access the encryption key. + KeyIdentifier *string + + // READ-ONLY; Auto key rotation status for a CMK enabled registry. + KeyRotationEnabled *bool + + // READ-ONLY; Timestamp of the last successful key rotation. + LastKeyRotationTimestamp *time.Time + + // READ-ONLY; The fully qualified key identifier that includes the version of the key that is actually used for encryption. + VersionedKeyIdentifier *string +} + +// NetworkRuleSet - The network rule set for a container registry. +type NetworkRuleSet struct { + // REQUIRED; The default action of allow or deny when no other rules match. + DefaultAction *DefaultAction + + // The IP ACL rules. + IPRules []*IPRule +} + +// OperationDefinition - The definition of a container registry operation. +type OperationDefinition struct { + // The display information for the container registry operation. + Display *OperationDisplayDefinition + + // This property indicates if the operation is an action or a data action ref: https://docs.microsoft.com/en-us/azure/role-based-access-control/role-definitions#management-and-data-operations + IsDataAction *bool + + // Operation name: {provider}/{resource}/{operation}. + Name *string + + // The origin information of the container registry operation. + Origin *string + + // The properties information for the container registry operation. + Properties *OperationPropertiesDefinition +} + +// OperationDisplayDefinition - The display information for a container registry operation. +type OperationDisplayDefinition struct { + // The description for the operation. + Description *string + + // The operation that users can perform. + Operation *string + + // The resource provider name: Microsoft.ContainerRegistry. + Provider *string + + // The resource on which the operation is performed. + Resource *string +} + +// OperationListResult - The result of a request to list container registry operations. +type OperationListResult struct { + // The URI that can be used to request the next list of container registry operations. + NextLink *string + + // The list of container registry operations. Since this list may be incomplete, the nextLink field should be used to request + // the next list of operations. + Value []*OperationDefinition +} + +// OperationLogSpecificationDefinition - The definition of Azure Monitoring log. +type OperationLogSpecificationDefinition struct { + // Log blob duration. + BlobDuration *string + + // Log display name. + DisplayName *string + + // Log name. + Name *string +} + +// OperationMetricSpecificationDefinition - The definition of Azure Monitoring metric. +type OperationMetricSpecificationDefinition struct { + // Metric aggregation type. + AggregationType *string + + // Metric description. + DisplayDescription *string + + // Metric display name. + DisplayName *string + + // Internal metric name. + InternalMetricName *string + + // Metric name. + Name *string + + // Metric unit. + Unit *string +} + +// OperationPropertiesDefinition - The definition of Azure Monitoring properties. +type OperationPropertiesDefinition struct { + // The definition of Azure Monitoring service. + ServiceSpecification *OperationServiceSpecificationDefinition +} + +// OperationServiceSpecificationDefinition - The definition of Azure Monitoring list. +type OperationServiceSpecificationDefinition struct { + // A list of Azure Monitoring log definitions. + LogSpecifications []*OperationLogSpecificationDefinition + + // A list of Azure Monitoring metrics definition. + MetricSpecifications []*OperationMetricSpecificationDefinition +} + +type OverrideTaskStepProperties struct { + // Gets or sets the collection of override arguments to be used when executing a build step. + Arguments []*Argument + + // The source context against which run has to be queued. + ContextPath *string + + // The file against which run has to be queued. + File *string + + // The name of the target build stage for the docker build. + Target *string + + // Base64 encoded update trigger token that will be attached with the base image trigger webhook. + UpdateTriggerToken *string + + // The collection of overridable values that can be passed when running a Task. + Values []*SetValue +} + +// PlatformProperties - The platform properties against which the run has to happen. +type PlatformProperties struct { + // REQUIRED; The operating system type required for the run. + OS *OS + + // The OS architecture. + Architecture *Architecture + + // Variant of the CPU. + Variant *Variant +} + +// PlatformUpdateParameters - The properties for updating the platform configuration. +type PlatformUpdateParameters struct { + // The OS architecture. + Architecture *Architecture + + // The operating system type required for the run. + OS *OS + + // Variant of the CPU. + Variant *Variant +} + +// Policies - The policies for a container registry. +type Policies struct { + // The export policy for a container registry. + ExportPolicy *ExportPolicy + + // The quarantine policy for a container registry. + QuarantinePolicy *QuarantinePolicy + + // The retention policy for a container registry. + RetentionPolicy *RetentionPolicy + + // The content trust policy for a container registry. + TrustPolicy *TrustPolicy +} + +// PrivateEndpoint - The Private Endpoint resource. +type PrivateEndpoint struct { + // This is private endpoint resource created with Microsoft.Network resource provider. + ID *string +} + +// PrivateEndpointConnection - An object that represents a private endpoint connection for a container registry. +type PrivateEndpointConnection struct { + // The properties of a private endpoint connection. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// PrivateEndpointConnectionListResult - The result of a request to list private endpoint connections for a container registry. +type PrivateEndpointConnectionListResult struct { + // The URI that can be used to request the next list of private endpoint connections. + NextLink *string + + // The list of private endpoint connections. Since this list may be incomplete, the nextLink field should be used to request + // the next list of private endpoint connections. + Value []*PrivateEndpointConnection +} + +// PrivateEndpointConnectionProperties - The properties of a private endpoint connection. +type PrivateEndpointConnectionProperties struct { + // The resource of private endpoint. + PrivateEndpoint *PrivateEndpoint + + // A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // READ-ONLY; The provisioning state of private endpoint connection resource. + ProvisioningState *ProvisioningState +} + +// PrivateLinkResource - A resource that supports private link capabilities. +type PrivateLinkResource struct { + // The resource ID. + ID *string + + // The name of the resource. + Name *string + + // A resource that supports private link capabilities. + Properties *PrivateLinkResourceProperties + + // READ-ONLY; The resource type is private link resource. + Type *string +} + +// PrivateLinkResourceListResult - The result of a request to list private link resources for a container registry. +type PrivateLinkResourceListResult struct { + // The URI that can be used to request the next list of private link resources. + NextLink *string + + // The list of private link resources. Since this list may be incomplete, the nextLink field should be used to request the + // next list of private link resources. + Value []*PrivateLinkResource +} + +// PrivateLinkResourceProperties - The properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource group id. + GroupID *string + + // The private link resource required member names. + RequiredMembers []*string + + // The private link resource Private link DNS zone name. + RequiredZoneNames []*string +} + +// PrivateLinkServiceConnectionState - The state of a private link service connection. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *ActionsRequired + + // The description for connection status. For example if connection is rejected it can indicate reason for rejection. + Description *string + + // The private link service connection status. + Status *ConnectionStatus +} + +// QuarantinePolicy - The quarantine policy for a container registry. +type QuarantinePolicy struct { + // The value that indicates whether the policy is enabled or not. + Status *PolicyStatus +} + +// RegenerateCredentialParameters - The parameters used to regenerate the login credential. +type RegenerateCredentialParameters struct { + // REQUIRED; Specifies name of the password which should be regenerated -- password or password2. + Name *PasswordName +} + +// Registry - An object that represents a container registry. +type Registry struct { + // REQUIRED; The location of the resource. This cannot be changed after the resource is created. + Location *string + + // REQUIRED; The SKU of the container registry. + SKU *SKU + + // The identity of the container registry. + Identity *IdentityProperties + + // The properties of the container registry. + Properties *RegistryProperties + + // The tags of the resource. + Tags map[string]*string + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// RegistryListCredentialsResult - The response from the ListCredentials operation. +type RegistryListCredentialsResult struct { + // The list of passwords for a container registry. + Passwords []*RegistryPassword + + // The username for a container registry. + Username *string +} + +// RegistryListResult - The result of a request to list container registries. +type RegistryListResult struct { + // The URI that can be used to request the next list of container registries. + NextLink *string + + // The list of container registries. Since this list may be incomplete, the nextLink field should be used to request the next + // list of container registries. + Value []*Registry +} + +// RegistryNameCheckRequest - A request to check whether a container registry name is available. +type RegistryNameCheckRequest struct { + // REQUIRED; The name of the container registry. + Name *string + + // CONSTANT; The resource type of the container registry. This field must be set to 'Microsoft.ContainerRegistry/registries'. + // Field has constant value "Microsoft.ContainerRegistry/registries", any specified value is ignored. + Type *string +} + +// RegistryNameStatus - The result of a request to check the availability of a container registry name. +type RegistryNameStatus struct { + // If any, the error message that provides more detail for the reason that the name is not available. + Message *string + + // The value that indicates whether the name is available. + NameAvailable *bool + + // If any, the reason that the name is not available. + Reason *string +} + +// RegistryPassword - The login password for the container registry. +type RegistryPassword struct { + // The password name. + Name *PasswordName + + // The password value. + Value *string +} + +// RegistryProperties - The properties of a container registry. +type RegistryProperties struct { + // The value that indicates whether the admin user is enabled. + AdminUserEnabled *bool + + // Enable a single data endpoint per region for serving data. + DataEndpointEnabled *bool + + // The encryption settings of container registry. + Encryption *EncryptionProperty + + // Whether to allow trusted Azure services to access a network restricted registry. + NetworkRuleBypassOptions *NetworkRuleBypassOptions + + // The network rule set for a container registry. + NetworkRuleSet *NetworkRuleSet + + // The policies for a container registry. + Policies *Policies + + // Whether or not public network access is allowed for the container registry. + PublicNetworkAccess *PublicNetworkAccess + + // Whether or not zone redundancy is enabled for this container registry + ZoneRedundancy *ZoneRedundancy + + // READ-ONLY; The creation date of the container registry in ISO8601 format. + CreationDate *time.Time + + // READ-ONLY; List of host names that will serve data when dataEndpointEnabled is true. + DataEndpointHostNames []*string + + // READ-ONLY; The URL that can be used to log into the container registry. + LoginServer *string + + // READ-ONLY; List of private endpoint connections for a container registry. + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; The provisioning state of the container registry at the time the operation was called. + ProvisioningState *ProvisioningState + + // READ-ONLY; The status of the container registry at the time the operation was called. + Status *Status +} + +// RegistryPropertiesUpdateParameters - The parameters for updating the properties of a container registry. +type RegistryPropertiesUpdateParameters struct { + // The value that indicates whether the admin user is enabled. + AdminUserEnabled *bool + + // Enable a single data endpoint per region for serving data. + DataEndpointEnabled *bool + + // The encryption settings of container registry. + Encryption *EncryptionProperty + + // Whether to allow trusted Azure services to access a network restricted registry. + NetworkRuleBypassOptions *NetworkRuleBypassOptions + + // The network rule set for a container registry. + NetworkRuleSet *NetworkRuleSet + + // The policies for a container registry. + Policies *Policies + + // Whether or not public network access is allowed for the container registry. + PublicNetworkAccess *PublicNetworkAccess +} + +// RegistryUpdateParameters - The parameters for updating a container registry. +type RegistryUpdateParameters struct { + // The identity of the container registry. + Identity *IdentityProperties + + // The properties that the container registry will be updated with. + Properties *RegistryPropertiesUpdateParameters + + // The SKU of the container registry. + SKU *SKU + + // The tags for the container registry. + Tags map[string]*string +} + +// RegistryUsage - The quota usage for a container registry. +type RegistryUsage struct { + // The current value of the usage. + CurrentValue *int64 + + // The limit of the usage. + Limit *int64 + + // The name of the usage. + Name *string + + // The unit of measurement. + Unit *RegistryUsageUnit +} + +// RegistryUsageListResult - The result of a request to get container registry quota usages. +type RegistryUsageListResult struct { + // The list of container registry quota usages. + Value []*RegistryUsage +} + +// Replication - An object that represents a replication for a container registry. +type Replication struct { + // REQUIRED; The location of the resource. This cannot be changed after the resource is created. + Location *string + + // The properties of the replication. + Properties *ReplicationProperties + + // The tags of the resource. + Tags map[string]*string + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// ReplicationListResult - The result of a request to list replications for a container registry. +type ReplicationListResult struct { + // The URI that can be used to request the next list of replications. + NextLink *string + + // The list of replications. Since this list may be incomplete, the nextLink field should be used to request the next list + // of replications. + Value []*Replication +} + +// ReplicationProperties - The properties of a replication. +type ReplicationProperties struct { + // Specifies whether the replication's regional endpoint is enabled. Requests will not be routed to a replication whose regional + // endpoint is disabled, however its data will continue to be synced with + // other replications. + RegionEndpointEnabled *bool + + // Whether or not zone redundancy is enabled for this container registry replication + ZoneRedundancy *ZoneRedundancy + + // READ-ONLY; The provisioning state of the replication at the time the operation was called. + ProvisioningState *ProvisioningState + + // READ-ONLY; The status of the replication at the time the operation was called. + Status *Status +} + +// ReplicationUpdateParameters - The parameters for updating a replication. +type ReplicationUpdateParameters struct { + // The parameters for updating a replication's properties + Properties *ReplicationUpdateParametersProperties + + // The tags for the replication. + Tags map[string]*string +} + +type ReplicationUpdateParametersProperties struct { + // Specifies whether the replication's regional endpoint is enabled. Requests will not be routed to a replication whose regional + // endpoint is disabled, however its data will continue to be synced with + // other replications. + RegionEndpointEnabled *bool +} + +// Request - The request that generated the event. +type Request struct { + // The IP or hostname and possibly port of the client connection that initiated the event. This is the RemoteAddr from the + // standard http request. + Addr *string + + // The externally accessible hostname of the registry instance, as specified by the http host header on incoming requests. + Host *string + + // The ID of the request that initiated the event. + ID *string + + // The request method that generated the event. + Method *string + + // The user agent header of the request. + Useragent *string +} + +// RetentionPolicy - The retention policy for a container registry. +type RetentionPolicy struct { + // The number of days to retain an untagged manifest after which it gets purged. + Days *int32 + + // The value that indicates whether the policy is enabled or not. + Status *PolicyStatus + + // READ-ONLY; The timestamp when the policy was last updated. + LastUpdatedTime *time.Time +} + +// Run resource properties +type Run struct { + // The properties of a run. + Properties *RunProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// RunFilter - Properties that are enabled for Odata querying on runs. +type RunFilter struct { + // The name of the agent pool that the run corresponds to. + AgentPoolName *string + + // The create time for a run. + CreateTime *time.Time + + // The time the run finished. + FinishTime *time.Time + + // The value that indicates whether archiving is enabled or not. + IsArchiveEnabled *bool + + // The list of comma-separated image manifests that were generated from the run. This is applicable if the run is of build + // type. + OutputImageManifests *string + + // The unique identifier for the run. + RunID *string + + // The type of run. + RunType *RunType + + // The current status of the run. + Status *RunStatus + + // The name of the task that the run corresponds to. + TaskName *string +} + +// RunGetLogResult - The result of get log link operation. +type RunGetLogResult struct { + // The link to logs in registry for a run on a azure container registry. + LogArtifactLink *string + + // The link to logs for a run on a azure container registry. + LogLink *string +} + +// RunListResult - Collection of runs. +type RunListResult struct { + // The URI that can be used to request the next set of paged results. + NextLink *string + + // The collection value. + Value []*Run +} + +// RunProperties - The properties for a run. +type RunProperties struct { + // The machine configuration of the run agent. + AgentConfiguration *AgentProperties + + // The dedicated agent pool for the run. + AgentPoolName *string + + // The time the run was scheduled. + CreateTime *time.Time + + // The list of custom registries that were logged in during this run. + CustomRegistries []*string + + // The time the run finished. + FinishTime *time.Time + + // The image update trigger that caused the run. This is applicable if the task has base image trigger configured. + ImageUpdateTrigger *ImageUpdateTrigger + + // The value that indicates whether archiving is enabled or not. + IsArchiveEnabled *bool + + // The last updated time for the run. + LastUpdatedTime *time.Time + + // The list of all images that were generated from the run. This is applicable if the run generates base image dependencies. + OutputImages []*ImageDescriptor + + // The platform properties against which the run will happen. + Platform *PlatformProperties + + // The provisioning state of a run. + ProvisioningState *ProvisioningState + + // The unique identifier for the run. + RunID *string + + // The type of run. + RunType *RunType + + // The scope of the credentials that were used to login to the source registry during this run. + SourceRegistryAuth *string + + // The source trigger that caused the run. + SourceTrigger *SourceTriggerDescriptor + + // The time the run started. + StartTime *time.Time + + // The current status of the run. + Status *RunStatus + + // The task against which run was scheduled. + Task *string + + // The timer trigger that caused the run. + TimerTrigger *TimerTriggerDescriptor + + // The update trigger token passed for the Run. + UpdateTriggerToken *string + + // READ-ONLY; The image description for the log artifact. + LogArtifact *ImageDescriptor + + // READ-ONLY; The error message received from backend systems after the run is scheduled. + RunErrorMessage *string +} + +// RunRequest - The request parameters for scheduling a run. +type RunRequest struct { + // REQUIRED; The type of the run request. + Type *string + + // The dedicated agent pool for the run. + AgentPoolName *string + + // The value that indicates whether archiving is enabled for the run or not. + IsArchiveEnabled *bool + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string +} + +// GetRunRequest implements the RunRequestClassification interface for type RunRequest. +func (r *RunRequest) GetRunRequest() *RunRequest { return r } + +// RunUpdateParameters - The set of run properties that can be updated. +type RunUpdateParameters struct { + // The value that indicates whether archiving is enabled or not. + IsArchiveEnabled *bool +} + +// SKU - The SKU of a container registry. +type SKU struct { + // REQUIRED; The SKU name of the container registry. Required for registry creation. + Name *SKUName + + // READ-ONLY; The SKU tier based on the SKU name. + Tier *SKUTier +} + +// ScopeMap - An object that represents a scope map for a container registry. +type ScopeMap struct { + // The properties of the scope map. + Properties *ScopeMapProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// ScopeMapListResult - The result of a request to list scope maps for a container registry. +type ScopeMapListResult struct { + // The URI that can be used to request the next list of scope maps. + NextLink *string + + // The list of scope maps. Since this list may be incomplete, the nextLink field should be used to request the next list of + // scope maps. + Value []*ScopeMap +} + +// ScopeMapProperties - The properties of a scope map. +type ScopeMapProperties struct { + // REQUIRED; The list of scoped permissions for registry artifacts. E.g. repositories/repository-name/content/read, repositories/repository-name/metadata/write + Actions []*string + + // The user friendly description of the scope map. + Description *string + + // READ-ONLY; The creation date of scope map. + CreationDate *time.Time + + // READ-ONLY; Provisioning state of the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The type of the scope map. E.g. BuildIn scope map. + Type *string +} + +// ScopeMapPropertiesUpdateParameters - The update parameters for scope map properties. +type ScopeMapPropertiesUpdateParameters struct { + // The list of scope permissions for registry artifacts. E.g. repositories/repository-name/pull, repositories/repository-name/delete + Actions []*string + + // The user friendly description of the scope map. + Description *string +} + +// ScopeMapUpdateParameters - The properties for updating the scope map. +type ScopeMapUpdateParameters struct { + // The update parameters for scope map properties. + Properties *ScopeMapPropertiesUpdateParameters +} + +// SecretObject - Describes the properties of a secret object value. +type SecretObject struct { + // The type of the secret object which determines how the value of the secret object has to be interpreted. + Type *SecretObjectType + + // The value of the secret. The format of this value will be determined based on the type of the secret object. If the type + // is Opaque, the value will be used as is without any modification. + Value *string +} + +// SetValue - The properties of a overridable value that can be passed to a task template. +type SetValue struct { + // REQUIRED; The name of the overridable value. + Name *string + + // REQUIRED; The overridable value. + Value *string + + // Flag to indicate whether the value represents a secret or not. + IsSecret *bool +} + +// Source - The registry node that generated the event. Put differently, while the actor initiates the event, the source generates +// it. +type Source struct { + // The IP or hostname and the port of the registry node that generated the event. Generally, this will be resolved by os.Hostname() + // along with the running port. + Addr *string + + // The running instance of an application. Changes after each restart. + InstanceID *string +} + +// SourceProperties - The properties of the source code repository. +type SourceProperties struct { + // REQUIRED; The full URL to the source code repository + RepositoryURL *string + + // REQUIRED; The type of source control service. + SourceControlType *SourceControlType + + // The branch name of the source code. + Branch *string + + // The authorization properties for accessing the source code repository and to set up webhooks for notifications. + SourceControlAuthProperties *AuthInfo +} + +// SourceRegistryCredentials - Describes the credential parameters for accessing the source registry. +type SourceRegistryCredentials struct { + // The authentication mode which determines the source registry login scope. The credentials for the source registry will + // be generated using the given scope. These credentials will be used to login to + // the source registry during the run. + LoginMode *SourceRegistryLoginMode +} + +// SourceTrigger - The properties of a source based trigger. +type SourceTrigger struct { + // REQUIRED; The name of the trigger. + Name *string + + // REQUIRED; The properties that describes the source(code) for the task. + SourceRepository *SourceProperties + + // REQUIRED; The source event corresponding to the trigger. + SourceTriggerEvents []*SourceTriggerEvent + + // The current status of trigger. + Status *TriggerStatus +} + +// SourceTriggerDescriptor - The source trigger that caused a run. +type SourceTriggerDescriptor struct { + // The branch name in the repository. + BranchName *string + + // The unique ID that identifies a commit. + CommitID *string + + // The event type of the trigger. + EventType *string + + // The unique ID of the trigger. + ID *string + + // The source control provider type. + ProviderType *string + + // The unique ID that identifies pull request. + PullRequestID *string + + // The repository URL. + RepositoryURL *string +} + +// SourceTriggerUpdateParameters - The properties for updating a source based trigger. +type SourceTriggerUpdateParameters struct { + // REQUIRED; The name of the trigger. + Name *string + + // The properties that describes the source(code) for the task. + SourceRepository *SourceUpdateParameters + + // The source event corresponding to the trigger. + SourceTriggerEvents []*SourceTriggerEvent + + // The current status of trigger. + Status *TriggerStatus +} + +// SourceUpdateParameters - The properties for updating the source code repository. +type SourceUpdateParameters struct { + // The branch name of the source code. + Branch *string + + // The full URL to the source code repository + RepositoryURL *string + + // The authorization properties for accessing the source code repository and to set up webhooks for notifications. + SourceControlAuthProperties *AuthInfoUpdateParameters + + // The type of source control service. + SourceControlType *SourceControlType +} + +// SourceUploadDefinition - The properties of a response to source upload request. +type SourceUploadDefinition struct { + // The relative path to the source. This is used to submit the subsequent queue build request. + RelativePath *string + + // The URL where the client can upload the source. + UploadURL *string +} + +// Status - The status of an Azure resource at the time the operation was called. +type Status struct { + // READ-ONLY; The short label for the status. + DisplayStatus *string + + // READ-ONLY; The detailed message for the status, including alerts and error messages. + Message *string + + // READ-ONLY; The timestamp when the status was changed to the current value. + Timestamp *time.Time +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource modification (UTC). + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *LastModifiedByType +} + +// Target - The target of the event. +type Target struct { + // The digest of the content, as defined by the Registry V2 HTTP API Specification. + Digest *string + + // The number of bytes of the content. Same as Size field. + Length *int64 + + // The MIME type of the referenced object. + MediaType *string + + // The name of the artifact. + Name *string + + // The repository name. + Repository *string + + // The number of bytes of the content. Same as Length field. + Size *int64 + + // The tag name. + Tag *string + + // The direct URL to the content. + URL *string + + // The version of the artifact. + Version *string +} + +// Task - The task that has the ARM resource and task properties. The task will have all information to schedule a run against +// it. +type Task struct { + // REQUIRED; The location of the resource. This cannot be changed after the resource is created. + Location *string + + // Identity for the resource. + Identity *IdentityProperties + + // The properties of a task. + Properties *TaskProperties + + // The tags of the resource. + Tags map[string]*string + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// TaskListResult - The collection of tasks. +type TaskListResult struct { + // The URI that can be used to request the next set of paged results. + NextLink *string + + // The collection value. + Value []*Task +} + +// TaskProperties - The properties of a task. +type TaskProperties struct { + // The machine configuration of the run agent. + AgentConfiguration *AgentProperties + + // The dedicated agent pool for the task. + AgentPoolName *string + + // The properties that describes a set of credentials that will be used when this run is invoked. + Credentials *Credentials + + // The value of this property indicates whether the task resource is system task or not. + IsSystemTask *bool + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string + + // The platform properties against which the run has to happen. + Platform *PlatformProperties + + // The current status of task. + Status *TaskStatus + + // The properties of a task step. + Step TaskStepPropertiesClassification + + // Run timeout in seconds. + Timeout *int32 + + // The properties that describe all triggers for the task. + Trigger *TriggerProperties + + // READ-ONLY; The creation date of task. + CreationDate *time.Time + + // READ-ONLY; The provisioning state of the task. + ProvisioningState *ProvisioningState +} + +// TaskPropertiesUpdateParameters - The properties for updating a task. +type TaskPropertiesUpdateParameters struct { + // The machine configuration of the run agent. + AgentConfiguration *AgentProperties + + // The dedicated agent pool for the task. + AgentPoolName *string + + // The parameters that describes a set of credentials that will be used when this run is invoked. + Credentials *Credentials + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string + + // The platform properties against which the run has to happen. + Platform *PlatformUpdateParameters + + // The current status of task. + Status *TaskStatus + + // The properties for updating a task step. + Step TaskStepUpdateParametersClassification + + // Run timeout in seconds. + Timeout *int32 + + // The properties for updating trigger properties. + Trigger *TriggerUpdateParameters +} + +// TaskRun - The task run that has the ARM resource and properties. The task run will have the information of request and +// result of a run. +type TaskRun struct { + // Identity for the resource. + Identity *IdentityProperties + + // The location of the resource + Location *string + + // The properties associated with the task run, i.e., request and result of the run + Properties *TaskRunProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// TaskRunListResult - The collection of task runs. +type TaskRunListResult struct { + // The URI that can be used to request the next set of paged results. + NextLink *string + + // The collection value. + Value []*TaskRun +} + +// TaskRunProperties - The properties of task run. +type TaskRunProperties struct { + // How the run should be forced to rerun even if the run request configuration has not changed + ForceUpdateTag *string + + // The request (parameters) for the run + RunRequest RunRequestClassification + + // READ-ONLY; The provisioning state of this task run + ProvisioningState *ProvisioningState + + // READ-ONLY; The result of this task run + RunResult *Run +} + +// TaskRunPropertiesUpdateParameters - The properties of a task run update parameters. +type TaskRunPropertiesUpdateParameters struct { + // How the run should be forced to rerun even if the run request configuration has not changed + ForceUpdateTag *string + + // The request (parameters) for the new run + RunRequest RunRequestClassification +} + +// TaskRunRequest - The parameters for a task run request. +type TaskRunRequest struct { + // REQUIRED; The resource ID of task against which run has to be queued. + TaskID *string + + // REQUIRED; The type of the run request. + Type *string + + // The dedicated agent pool for the run. + AgentPoolName *string + + // The value that indicates whether archiving is enabled for the run or not. + IsArchiveEnabled *bool + + // The template that describes the repository and tag information for run log artifact. + LogTemplate *string + + // Set of overridable parameters that can be passed when running a Task. + OverrideTaskStepProperties *OverrideTaskStepProperties +} + +// GetRunRequest implements the RunRequestClassification interface for type TaskRunRequest. +func (t *TaskRunRequest) GetRunRequest() *RunRequest { + return &RunRequest{ + AgentPoolName: t.AgentPoolName, + IsArchiveEnabled: t.IsArchiveEnabled, + LogTemplate: t.LogTemplate, + Type: t.Type, + } +} + +// TaskRunUpdateParameters - The parameters for updating a task run. +type TaskRunUpdateParameters struct { + // Identity for the resource. + Identity *IdentityProperties + + // The location of the resource + Location *string + + // The properties for updating a task run. + Properties *TaskRunPropertiesUpdateParameters + + // The ARM resource tags. + Tags map[string]*string +} + +// TaskStepProperties - Base properties for any task step. +type TaskStepProperties struct { + // REQUIRED; The type of the step. + Type *StepType + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string + + // READ-ONLY; List of base image dependencies for a step. + BaseImageDependencies []*BaseImageDependency +} + +// GetTaskStepProperties implements the TaskStepPropertiesClassification interface for type TaskStepProperties. +func (t *TaskStepProperties) GetTaskStepProperties() *TaskStepProperties { return t } + +// TaskStepUpdateParameters - Base properties for updating any task step. +type TaskStepUpdateParameters struct { + // REQUIRED; The type of the step. + Type *StepType + + // The token (git PAT or SAS token of storage account blob) associated with the context for a step. + ContextAccessToken *string + + // The URL(absolute or relative) of the source context for the task step. + ContextPath *string +} + +// GetTaskStepUpdateParameters implements the TaskStepUpdateParametersClassification interface for type TaskStepUpdateParameters. +func (t *TaskStepUpdateParameters) GetTaskStepUpdateParameters() *TaskStepUpdateParameters { return t } + +// TaskUpdateParameters - The parameters for updating a task. +type TaskUpdateParameters struct { + // Identity for the resource. + Identity *IdentityProperties + + // The properties for updating a task. + Properties *TaskPropertiesUpdateParameters + + // The ARM resource tags. + Tags map[string]*string +} + +// TimerTrigger - The properties of a timer trigger. +type TimerTrigger struct { + // REQUIRED; The name of the trigger. + Name *string + + // REQUIRED; The CRON expression for the task schedule + Schedule *string + + // The current status of trigger. + Status *TriggerStatus +} + +type TimerTriggerDescriptor struct { + // The occurrence that triggered the run. + ScheduleOccurrence *string + + // The timer trigger name that caused the run. + TimerTriggerName *string +} + +// TimerTriggerUpdateParameters - The properties for updating a timer trigger. +type TimerTriggerUpdateParameters struct { + // REQUIRED; The name of the trigger. + Name *string + + // The CRON expression for the task schedule + Schedule *string + + // The current status of trigger. + Status *TriggerStatus +} + +// Token - An object that represents a token for a container registry. +type Token struct { + // The properties of the token. + Properties *TokenProperties + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// TokenCertificate - The properties of a certificate used for authenticating a token. +type TokenCertificate struct { + // Base 64 encoded string of the public certificate1 in PEM format that will be used for authenticating the token. + EncodedPemCertificate *string + + // The expiry datetime of the certificate. + Expiry *time.Time + Name *TokenCertificateName + + // The thumbprint of the certificate. + Thumbprint *string +} + +// TokenCredentialsProperties - The properties of the credentials that can be used for authenticating the token. +type TokenCredentialsProperties struct { + Certificates []*TokenCertificate + Passwords []*TokenPassword +} + +// TokenListResult - The result of a request to list tokens for a container registry. +type TokenListResult struct { + // The URI that can be used to request the next list of tokens. + NextLink *string + + // The list of tokens. Since this list may be incomplete, the nextLink field should be used to request the next list of tokens. + Value []*Token +} + +// TokenPassword - The password that will be used for authenticating the token of a container registry. +type TokenPassword struct { + // The creation datetime of the password. + CreationTime *time.Time + + // The expiry datetime of the password. + Expiry *time.Time + + // The password name "password1" or "password2" + Name *TokenPasswordName + + // READ-ONLY; The password value. + Value *string +} + +// TokenProperties - The properties of a token. +type TokenProperties struct { + // The credentials that can be used for authenticating the token. + Credentials *TokenCredentialsProperties + + // The resource ID of the scope map to which the token will be associated with. + ScopeMapID *string + + // The status of the token example enabled or disabled. + Status *TokenStatus + + // READ-ONLY; The creation date of scope map. + CreationDate *time.Time + + // READ-ONLY; Provisioning state of the resource. + ProvisioningState *ProvisioningState +} + +// TokenUpdateParameters - The parameters for updating a token. +type TokenUpdateParameters struct { + // The properties of the token update parameters. + Properties *TokenUpdateProperties +} + +// TokenUpdateProperties - The parameters for updating token properties. +type TokenUpdateProperties struct { + // The credentials that can be used for authenticating the token. + Credentials *TokenCredentialsProperties + + // The resource ID of the scope map to which the token will be associated with. + ScopeMapID *string + + // The status of the token example enabled or disabled. + Status *TokenStatus +} + +// TriggerProperties - The properties of a trigger. +type TriggerProperties struct { + // The trigger based on base image dependencies. + BaseImageTrigger *BaseImageTrigger + + // The collection of triggers based on source code repository. + SourceTriggers []*SourceTrigger + + // The collection of timer triggers. + TimerTriggers []*TimerTrigger +} + +// TriggerUpdateParameters - The properties for updating triggers. +type TriggerUpdateParameters struct { + // The trigger based on base image dependencies. + BaseImageTrigger *BaseImageTriggerUpdateParameters + + // The collection of triggers based on source code repository. + SourceTriggers []*SourceTriggerUpdateParameters + + // The collection of timer triggers. + TimerTriggers []*TimerTriggerUpdateParameters +} + +// TrustPolicy - The content trust policy for a container registry. +type TrustPolicy struct { + // The value that indicates whether the policy is enabled or not. + Status *PolicyStatus + + // The type of trust policy. + Type *TrustPolicyType +} + +type UserIdentityProperties struct { + // READ-ONLY; The client id of user assigned identity. + ClientID *string + + // READ-ONLY; The principal id of user assigned identity. + PrincipalID *string +} + +// Webhook - An object that represents a webhook for a container registry. +type Webhook struct { + // REQUIRED; The location of the resource. This cannot be changed after the resource is created. + Location *string + + // The properties of the webhook. + Properties *WebhookProperties + + // The tags of the resource. + Tags map[string]*string + + // READ-ONLY; The resource ID. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. + Type *string +} + +// WebhookCreateParameters - The parameters for creating a webhook. +type WebhookCreateParameters struct { + // REQUIRED; The location of the webhook. This cannot be changed after the resource is created. + Location *string + + // The properties that the webhook will be created with. + Properties *WebhookPropertiesCreateParameters + + // The tags for the webhook. + Tags map[string]*string +} + +// WebhookListResult - The result of a request to list webhooks for a container registry. +type WebhookListResult struct { + // The URI that can be used to request the next list of webhooks. + NextLink *string + + // The list of webhooks. Since this list may be incomplete, the nextLink field should be used to request the next list of + // webhooks. + Value []*Webhook +} + +// WebhookProperties - The properties of a webhook. +type WebhookProperties struct { + // REQUIRED; The list of actions that trigger the webhook to post notifications. + Actions []*WebhookAction + + // The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository + // 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to + // 'foo:latest'. Empty means all events. + Scope *string + + // The status of the webhook at the time the operation was called. + Status *WebhookStatus + + // READ-ONLY; The provisioning state of the webhook at the time the operation was called. + ProvisioningState *ProvisioningState +} + +// WebhookPropertiesCreateParameters - The parameters for creating the properties of a webhook. +type WebhookPropertiesCreateParameters struct { + // REQUIRED; The list of actions that trigger the webhook to post notifications. + Actions []*WebhookAction + + // REQUIRED; The service URI for the webhook to post notifications. + ServiceURI *string + + // Custom headers that will be added to the webhook notifications. + CustomHeaders map[string]*string + + // The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository + // 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to + // 'foo:latest'. Empty means all events. + Scope *string + + // The status of the webhook at the time the operation was called. + Status *WebhookStatus +} + +// WebhookPropertiesUpdateParameters - The parameters for updating the properties of a webhook. +type WebhookPropertiesUpdateParameters struct { + // The list of actions that trigger the webhook to post notifications. + Actions []*WebhookAction + + // Custom headers that will be added to the webhook notifications. + CustomHeaders map[string]*string + + // The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository + // 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to + // 'foo:latest'. Empty means all events. + Scope *string + + // The service URI for the webhook to post notifications. + ServiceURI *string + + // The status of the webhook at the time the operation was called. + Status *WebhookStatus +} + +// WebhookUpdateParameters - The parameters for updating a webhook. +type WebhookUpdateParameters struct { + // The properties that the webhook will be updated with. + Properties *WebhookPropertiesUpdateParameters + + // The tags for the webhook. + Tags map[string]*string +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models_serde.go new file mode 100644 index 0000000000..19e9b7a57d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/models_serde.go @@ -0,0 +1,6147 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Actor. +func (a Actor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Actor. +func (a *Actor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentPool. +func (a AgentPool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentPool. +func (a *AgentPool) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentPoolListResult. +func (a AgentPoolListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentPoolListResult. +func (a *AgentPoolListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentPoolProperties. +func (a AgentPoolProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", a.Count) + populate(objectMap, "os", a.OS) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "tier", a.Tier) + populate(objectMap, "virtualNetworkSubnetResourceId", a.VirtualNetworkSubnetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentPoolProperties. +func (a *AgentPoolProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &a.Count) + delete(rawMsg, key) + case "os": + err = unpopulate(val, "OS", &a.OS) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &a.Tier) + delete(rawMsg, key) + case "virtualNetworkSubnetResourceId": + err = unpopulate(val, "VirtualNetworkSubnetResourceID", &a.VirtualNetworkSubnetResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentPoolPropertiesUpdateParameters. +func (a AgentPoolPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", a.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentPoolPropertiesUpdateParameters. +func (a *AgentPoolPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &a.Count) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentPoolQueueStatus. +func (a AgentPoolQueueStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", a.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentPoolQueueStatus. +func (a *AgentPoolQueueStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &a.Count) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentPoolUpdateParameters. +func (a AgentPoolUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentPoolUpdateParameters. +func (a *AgentPoolUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentProperties. +func (a AgentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cpu", a.CPU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentProperties. +func (a *AgentProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cpu": + err = unpopulate(val, "CPU", &a.CPU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Argument. +func (a Argument) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isSecret", a.IsSecret) + populate(objectMap, "name", a.Name) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Argument. +func (a *Argument) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isSecret": + err = unpopulate(val, "IsSecret", &a.IsSecret) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthCredential. +func (a AuthCredential) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "credentialHealth", a.CredentialHealth) + populate(objectMap, "name", a.Name) + populate(objectMap, "passwordSecretIdentifier", a.PasswordSecretIdentifier) + populate(objectMap, "usernameSecretIdentifier", a.UsernameSecretIdentifier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthCredential. +func (a *AuthCredential) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "credentialHealth": + err = unpopulate(val, "CredentialHealth", &a.CredentialHealth) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "passwordSecretIdentifier": + err = unpopulate(val, "PasswordSecretIdentifier", &a.PasswordSecretIdentifier) + delete(rawMsg, key) + case "usernameSecretIdentifier": + err = unpopulate(val, "UsernameSecretIdentifier", &a.UsernameSecretIdentifier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthInfo. +func (a AuthInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "expiresIn", a.ExpiresIn) + populate(objectMap, "refreshToken", a.RefreshToken) + populate(objectMap, "scope", a.Scope) + populate(objectMap, "token", a.Token) + populate(objectMap, "tokenType", a.TokenType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthInfo. +func (a *AuthInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiresIn": + err = unpopulate(val, "ExpiresIn", &a.ExpiresIn) + delete(rawMsg, key) + case "refreshToken": + err = unpopulate(val, "RefreshToken", &a.RefreshToken) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &a.Scope) + delete(rawMsg, key) + case "token": + err = unpopulate(val, "Token", &a.Token) + delete(rawMsg, key) + case "tokenType": + err = unpopulate(val, "TokenType", &a.TokenType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthInfoUpdateParameters. +func (a AuthInfoUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "expiresIn", a.ExpiresIn) + populate(objectMap, "refreshToken", a.RefreshToken) + populate(objectMap, "scope", a.Scope) + populate(objectMap, "token", a.Token) + populate(objectMap, "tokenType", a.TokenType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthInfoUpdateParameters. +func (a *AuthInfoUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiresIn": + err = unpopulate(val, "ExpiresIn", &a.ExpiresIn) + delete(rawMsg, key) + case "refreshToken": + err = unpopulate(val, "RefreshToken", &a.RefreshToken) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &a.Scope) + delete(rawMsg, key) + case "token": + err = unpopulate(val, "Token", &a.Token) + delete(rawMsg, key) + case "tokenType": + err = unpopulate(val, "TokenType", &a.TokenType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BaseImageDependency. +func (b BaseImageDependency) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "digest", b.Digest) + populate(objectMap, "registry", b.Registry) + populate(objectMap, "repository", b.Repository) + populate(objectMap, "tag", b.Tag) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BaseImageDependency. +func (b *BaseImageDependency) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "digest": + err = unpopulate(val, "Digest", &b.Digest) + delete(rawMsg, key) + case "registry": + err = unpopulate(val, "Registry", &b.Registry) + delete(rawMsg, key) + case "repository": + err = unpopulate(val, "Repository", &b.Repository) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &b.Tag) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BaseImageTrigger. +func (b BaseImageTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageTriggerType", b.BaseImageTriggerType) + populate(objectMap, "name", b.Name) + populate(objectMap, "status", b.Status) + populate(objectMap, "updateTriggerEndpoint", b.UpdateTriggerEndpoint) + populate(objectMap, "updateTriggerPayloadType", b.UpdateTriggerPayloadType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BaseImageTrigger. +func (b *BaseImageTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageTriggerType": + err = unpopulate(val, "BaseImageTriggerType", &b.BaseImageTriggerType) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &b.Status) + delete(rawMsg, key) + case "updateTriggerEndpoint": + err = unpopulate(val, "UpdateTriggerEndpoint", &b.UpdateTriggerEndpoint) + delete(rawMsg, key) + case "updateTriggerPayloadType": + err = unpopulate(val, "UpdateTriggerPayloadType", &b.UpdateTriggerPayloadType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BaseImageTriggerUpdateParameters. +func (b BaseImageTriggerUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageTriggerType", b.BaseImageTriggerType) + populate(objectMap, "name", b.Name) + populate(objectMap, "status", b.Status) + populate(objectMap, "updateTriggerEndpoint", b.UpdateTriggerEndpoint) + populate(objectMap, "updateTriggerPayloadType", b.UpdateTriggerPayloadType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BaseImageTriggerUpdateParameters. +func (b *BaseImageTriggerUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageTriggerType": + err = unpopulate(val, "BaseImageTriggerType", &b.BaseImageTriggerType) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &b.Status) + delete(rawMsg, key) + case "updateTriggerEndpoint": + err = unpopulate(val, "UpdateTriggerEndpoint", &b.UpdateTriggerEndpoint) + delete(rawMsg, key) + case "updateTriggerPayloadType": + err = unpopulate(val, "UpdateTriggerPayloadType", &b.UpdateTriggerPayloadType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CacheRule. +func (c CacheRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CacheRule. +func (c *CacheRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CacheRuleProperties. +func (c CacheRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "creationDate", c.CreationDate) + populate(objectMap, "credentialSetResourceId", c.CredentialSetResourceID) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "sourceRepository", c.SourceRepository) + populate(objectMap, "targetRepository", c.TargetRepository) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CacheRuleProperties. +func (c *CacheRuleProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationDate": + err = unpopulateDateTimeRFC3339(val, "CreationDate", &c.CreationDate) + delete(rawMsg, key) + case "credentialSetResourceId": + err = unpopulate(val, "CredentialSetResourceID", &c.CredentialSetResourceID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "sourceRepository": + err = unpopulate(val, "SourceRepository", &c.SourceRepository) + delete(rawMsg, key) + case "targetRepository": + err = unpopulate(val, "TargetRepository", &c.TargetRepository) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CacheRuleUpdateParameters. +func (c CacheRuleUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CacheRuleUpdateParameters. +func (c *CacheRuleUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CacheRuleUpdateProperties. +func (c CacheRuleUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "credentialSetResourceId", c.CredentialSetResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CacheRuleUpdateProperties. +func (c *CacheRuleUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "credentialSetResourceId": + err = unpopulate(val, "CredentialSetResourceID", &c.CredentialSetResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CacheRulesListResult. +func (c CacheRulesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CacheRulesListResult. +func (c *CacheRulesListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CallbackConfig. +func (c CallbackConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customHeaders", c.CustomHeaders) + populate(objectMap, "serviceUri", c.ServiceURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CallbackConfig. +func (c *CallbackConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customHeaders": + err = unpopulate(val, "CustomHeaders", &c.CustomHeaders) + delete(rawMsg, key) + case "serviceUri": + err = unpopulate(val, "ServiceURI", &c.ServiceURI) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CredentialHealth. +func (c CredentialHealth) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorCode", c.ErrorCode) + populate(objectMap, "errorMessage", c.ErrorMessage) + populate(objectMap, "status", c.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CredentialHealth. +func (c *CredentialHealth) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "errorCode": + err = unpopulate(val, "ErrorCode", &c.ErrorCode) + delete(rawMsg, key) + case "errorMessage": + err = unpopulate(val, "ErrorMessage", &c.ErrorMessage) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CredentialSet. +func (c CredentialSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CredentialSet. +func (c *CredentialSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CredentialSetListResult. +func (c CredentialSetListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CredentialSetListResult. +func (c *CredentialSetListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CredentialSetProperties. +func (c CredentialSetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authCredentials", c.AuthCredentials) + populateDateTimeRFC3339(objectMap, "creationDate", c.CreationDate) + populate(objectMap, "loginServer", c.LoginServer) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CredentialSetProperties. +func (c *CredentialSetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authCredentials": + err = unpopulate(val, "AuthCredentials", &c.AuthCredentials) + delete(rawMsg, key) + case "creationDate": + err = unpopulateDateTimeRFC3339(val, "CreationDate", &c.CreationDate) + delete(rawMsg, key) + case "loginServer": + err = unpopulate(val, "LoginServer", &c.LoginServer) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CredentialSetUpdateParameters. +func (c CredentialSetUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CredentialSetUpdateParameters. +func (c *CredentialSetUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CredentialSetUpdateProperties. +func (c CredentialSetUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authCredentials", c.AuthCredentials) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CredentialSetUpdateProperties. +func (c *CredentialSetUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authCredentials": + err = unpopulate(val, "AuthCredentials", &c.AuthCredentials) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Credentials. +func (c Credentials) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customRegistries", c.CustomRegistries) + populate(objectMap, "sourceRegistry", c.SourceRegistry) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Credentials. +func (c *Credentials) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customRegistries": + err = unpopulate(val, "CustomRegistries", &c.CustomRegistries) + delete(rawMsg, key) + case "sourceRegistry": + err = unpopulate(val, "SourceRegistry", &c.SourceRegistry) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomRegistryCredentials. +func (c CustomRegistryCredentials) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "password", c.Password) + populate(objectMap, "userName", c.UserName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomRegistryCredentials. +func (c *CustomRegistryCredentials) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "userName": + err = unpopulate(val, "UserName", &c.UserName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DockerBuildRequest. +func (d DockerBuildRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentConfiguration", d.AgentConfiguration) + populate(objectMap, "agentPoolName", d.AgentPoolName) + populate(objectMap, "arguments", d.Arguments) + populate(objectMap, "credentials", d.Credentials) + populate(objectMap, "dockerFilePath", d.DockerFilePath) + populate(objectMap, "imageNames", d.ImageNames) + populate(objectMap, "isArchiveEnabled", d.IsArchiveEnabled) + populate(objectMap, "isPushEnabled", d.IsPushEnabled) + populate(objectMap, "logTemplate", d.LogTemplate) + populate(objectMap, "noCache", d.NoCache) + populate(objectMap, "platform", d.Platform) + populate(objectMap, "sourceLocation", d.SourceLocation) + populate(objectMap, "target", d.Target) + populate(objectMap, "timeout", d.Timeout) + objectMap["type"] = "DockerBuildRequest" + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DockerBuildRequest. +func (d *DockerBuildRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentConfiguration": + err = unpopulate(val, "AgentConfiguration", &d.AgentConfiguration) + delete(rawMsg, key) + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &d.AgentPoolName) + delete(rawMsg, key) + case "arguments": + err = unpopulate(val, "Arguments", &d.Arguments) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &d.Credentials) + delete(rawMsg, key) + case "dockerFilePath": + err = unpopulate(val, "DockerFilePath", &d.DockerFilePath) + delete(rawMsg, key) + case "imageNames": + err = unpopulate(val, "ImageNames", &d.ImageNames) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &d.IsArchiveEnabled) + delete(rawMsg, key) + case "isPushEnabled": + err = unpopulate(val, "IsPushEnabled", &d.IsPushEnabled) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &d.LogTemplate) + delete(rawMsg, key) + case "noCache": + err = unpopulate(val, "NoCache", &d.NoCache) + delete(rawMsg, key) + case "platform": + err = unpopulate(val, "Platform", &d.Platform) + delete(rawMsg, key) + case "sourceLocation": + err = unpopulate(val, "SourceLocation", &d.SourceLocation) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &d.Target) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &d.Timeout) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DockerBuildStep. +func (d DockerBuildStep) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "arguments", d.Arguments) + populate(objectMap, "baseImageDependencies", d.BaseImageDependencies) + populate(objectMap, "contextAccessToken", d.ContextAccessToken) + populate(objectMap, "contextPath", d.ContextPath) + populate(objectMap, "dockerFilePath", d.DockerFilePath) + populate(objectMap, "imageNames", d.ImageNames) + populate(objectMap, "isPushEnabled", d.IsPushEnabled) + populate(objectMap, "noCache", d.NoCache) + populate(objectMap, "target", d.Target) + objectMap["type"] = StepTypeDocker + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DockerBuildStep. +func (d *DockerBuildStep) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "arguments": + err = unpopulate(val, "Arguments", &d.Arguments) + delete(rawMsg, key) + case "baseImageDependencies": + err = unpopulate(val, "BaseImageDependencies", &d.BaseImageDependencies) + delete(rawMsg, key) + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &d.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &d.ContextPath) + delete(rawMsg, key) + case "dockerFilePath": + err = unpopulate(val, "DockerFilePath", &d.DockerFilePath) + delete(rawMsg, key) + case "imageNames": + err = unpopulate(val, "ImageNames", &d.ImageNames) + delete(rawMsg, key) + case "isPushEnabled": + err = unpopulate(val, "IsPushEnabled", &d.IsPushEnabled) + delete(rawMsg, key) + case "noCache": + err = unpopulate(val, "NoCache", &d.NoCache) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &d.Target) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DockerBuildStepUpdateParameters. +func (d DockerBuildStepUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "arguments", d.Arguments) + populate(objectMap, "contextAccessToken", d.ContextAccessToken) + populate(objectMap, "contextPath", d.ContextPath) + populate(objectMap, "dockerFilePath", d.DockerFilePath) + populate(objectMap, "imageNames", d.ImageNames) + populate(objectMap, "isPushEnabled", d.IsPushEnabled) + populate(objectMap, "noCache", d.NoCache) + populate(objectMap, "target", d.Target) + objectMap["type"] = StepTypeDocker + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DockerBuildStepUpdateParameters. +func (d *DockerBuildStepUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "arguments": + err = unpopulate(val, "Arguments", &d.Arguments) + delete(rawMsg, key) + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &d.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &d.ContextPath) + delete(rawMsg, key) + case "dockerFilePath": + err = unpopulate(val, "DockerFilePath", &d.DockerFilePath) + delete(rawMsg, key) + case "imageNames": + err = unpopulate(val, "ImageNames", &d.ImageNames) + delete(rawMsg, key) + case "isPushEnabled": + err = unpopulate(val, "IsPushEnabled", &d.IsPushEnabled) + delete(rawMsg, key) + case "noCache": + err = unpopulate(val, "NoCache", &d.NoCache) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &d.Target) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncodedTaskRunRequest. +func (e EncodedTaskRunRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentConfiguration", e.AgentConfiguration) + populate(objectMap, "agentPoolName", e.AgentPoolName) + populate(objectMap, "credentials", e.Credentials) + populate(objectMap, "encodedTaskContent", e.EncodedTaskContent) + populate(objectMap, "encodedValuesContent", e.EncodedValuesContent) + populate(objectMap, "isArchiveEnabled", e.IsArchiveEnabled) + populate(objectMap, "logTemplate", e.LogTemplate) + populate(objectMap, "platform", e.Platform) + populate(objectMap, "sourceLocation", e.SourceLocation) + populate(objectMap, "timeout", e.Timeout) + objectMap["type"] = "EncodedTaskRunRequest" + populate(objectMap, "values", e.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncodedTaskRunRequest. +func (e *EncodedTaskRunRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentConfiguration": + err = unpopulate(val, "AgentConfiguration", &e.AgentConfiguration) + delete(rawMsg, key) + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &e.AgentPoolName) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &e.Credentials) + delete(rawMsg, key) + case "encodedTaskContent": + err = unpopulate(val, "EncodedTaskContent", &e.EncodedTaskContent) + delete(rawMsg, key) + case "encodedValuesContent": + err = unpopulate(val, "EncodedValuesContent", &e.EncodedValuesContent) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &e.IsArchiveEnabled) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &e.LogTemplate) + delete(rawMsg, key) + case "platform": + err = unpopulate(val, "Platform", &e.Platform) + delete(rawMsg, key) + case "sourceLocation": + err = unpopulate(val, "SourceLocation", &e.SourceLocation) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &e.Timeout) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &e.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncodedTaskStep. +func (e EncodedTaskStep) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageDependencies", e.BaseImageDependencies) + populate(objectMap, "contextAccessToken", e.ContextAccessToken) + populate(objectMap, "contextPath", e.ContextPath) + populate(objectMap, "encodedTaskContent", e.EncodedTaskContent) + populate(objectMap, "encodedValuesContent", e.EncodedValuesContent) + objectMap["type"] = StepTypeEncodedTask + populate(objectMap, "values", e.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncodedTaskStep. +func (e *EncodedTaskStep) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageDependencies": + err = unpopulate(val, "BaseImageDependencies", &e.BaseImageDependencies) + delete(rawMsg, key) + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &e.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &e.ContextPath) + delete(rawMsg, key) + case "encodedTaskContent": + err = unpopulate(val, "EncodedTaskContent", &e.EncodedTaskContent) + delete(rawMsg, key) + case "encodedValuesContent": + err = unpopulate(val, "EncodedValuesContent", &e.EncodedValuesContent) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &e.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncodedTaskStepUpdateParameters. +func (e EncodedTaskStepUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contextAccessToken", e.ContextAccessToken) + populate(objectMap, "contextPath", e.ContextPath) + populate(objectMap, "encodedTaskContent", e.EncodedTaskContent) + populate(objectMap, "encodedValuesContent", e.EncodedValuesContent) + objectMap["type"] = StepTypeEncodedTask + populate(objectMap, "values", e.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncodedTaskStepUpdateParameters. +func (e *EncodedTaskStepUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &e.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &e.ContextPath) + delete(rawMsg, key) + case "encodedTaskContent": + err = unpopulate(val, "EncodedTaskContent", &e.EncodedTaskContent) + delete(rawMsg, key) + case "encodedValuesContent": + err = unpopulate(val, "EncodedValuesContent", &e.EncodedValuesContent) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &e.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionProperty. +func (e EncryptionProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyVaultProperties", e.KeyVaultProperties) + populate(objectMap, "status", e.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionProperty. +func (e *EncryptionProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyVaultProperties": + err = unpopulate(val, "KeyVaultProperties", &e.KeyVaultProperties) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &e.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Event. +func (e Event) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "eventRequestMessage", e.EventRequestMessage) + populate(objectMap, "eventResponseMessage", e.EventResponseMessage) + populate(objectMap, "id", e.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Event. +func (e *Event) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "eventRequestMessage": + err = unpopulate(val, "EventRequestMessage", &e.EventRequestMessage) + delete(rawMsg, key) + case "eventResponseMessage": + err = unpopulate(val, "EventResponseMessage", &e.EventResponseMessage) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EventContent. +func (e EventContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", e.Action) + populate(objectMap, "actor", e.Actor) + populate(objectMap, "id", e.ID) + populate(objectMap, "request", e.Request) + populate(objectMap, "source", e.Source) + populate(objectMap, "target", e.Target) + populateDateTimeRFC3339(objectMap, "timestamp", e.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventContent. +func (e *EventContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &e.Action) + delete(rawMsg, key) + case "actor": + err = unpopulate(val, "Actor", &e.Actor) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "request": + err = unpopulate(val, "Request", &e.Request) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &e.Source) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &e.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EventInfo. +func (e EventInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventInfo. +func (e *EventInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EventListResult. +func (e EventListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventListResult. +func (e *EventListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EventRequestMessage. +func (e EventRequestMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "content", e.Content) + populate(objectMap, "headers", e.Headers) + populate(objectMap, "method", e.Method) + populate(objectMap, "requestUri", e.RequestURI) + populate(objectMap, "version", e.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventRequestMessage. +func (e *EventRequestMessage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "content": + err = unpopulate(val, "Content", &e.Content) + delete(rawMsg, key) + case "headers": + err = unpopulate(val, "Headers", &e.Headers) + delete(rawMsg, key) + case "method": + err = unpopulate(val, "Method", &e.Method) + delete(rawMsg, key) + case "requestUri": + err = unpopulate(val, "RequestURI", &e.RequestURI) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &e.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EventResponseMessage. +func (e EventResponseMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "content", e.Content) + populate(objectMap, "headers", e.Headers) + populate(objectMap, "reasonPhrase", e.ReasonPhrase) + populate(objectMap, "statusCode", e.StatusCode) + populate(objectMap, "version", e.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventResponseMessage. +func (e *EventResponseMessage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "content": + err = unpopulate(val, "Content", &e.Content) + delete(rawMsg, key) + case "headers": + err = unpopulate(val, "Headers", &e.Headers) + delete(rawMsg, key) + case "reasonPhrase": + err = unpopulate(val, "ReasonPhrase", &e.ReasonPhrase) + delete(rawMsg, key) + case "statusCode": + err = unpopulate(val, "StatusCode", &e.StatusCode) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &e.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportPolicy. +func (e ExportPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", e.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportPolicy. +func (e *ExportPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "status": + err = unpopulate(val, "Status", &e.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileTaskRunRequest. +func (f FileTaskRunRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentConfiguration", f.AgentConfiguration) + populate(objectMap, "agentPoolName", f.AgentPoolName) + populate(objectMap, "credentials", f.Credentials) + populate(objectMap, "isArchiveEnabled", f.IsArchiveEnabled) + populate(objectMap, "logTemplate", f.LogTemplate) + populate(objectMap, "platform", f.Platform) + populate(objectMap, "sourceLocation", f.SourceLocation) + populate(objectMap, "taskFilePath", f.TaskFilePath) + populate(objectMap, "timeout", f.Timeout) + objectMap["type"] = "FileTaskRunRequest" + populate(objectMap, "values", f.Values) + populate(objectMap, "valuesFilePath", f.ValuesFilePath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileTaskRunRequest. +func (f *FileTaskRunRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentConfiguration": + err = unpopulate(val, "AgentConfiguration", &f.AgentConfiguration) + delete(rawMsg, key) + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &f.AgentPoolName) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &f.Credentials) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &f.IsArchiveEnabled) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &f.LogTemplate) + delete(rawMsg, key) + case "platform": + err = unpopulate(val, "Platform", &f.Platform) + delete(rawMsg, key) + case "sourceLocation": + err = unpopulate(val, "SourceLocation", &f.SourceLocation) + delete(rawMsg, key) + case "taskFilePath": + err = unpopulate(val, "TaskFilePath", &f.TaskFilePath) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &f.Timeout) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &f.Values) + delete(rawMsg, key) + case "valuesFilePath": + err = unpopulate(val, "ValuesFilePath", &f.ValuesFilePath) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileTaskStep. +func (f FileTaskStep) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageDependencies", f.BaseImageDependencies) + populate(objectMap, "contextAccessToken", f.ContextAccessToken) + populate(objectMap, "contextPath", f.ContextPath) + populate(objectMap, "taskFilePath", f.TaskFilePath) + objectMap["type"] = StepTypeFileTask + populate(objectMap, "values", f.Values) + populate(objectMap, "valuesFilePath", f.ValuesFilePath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileTaskStep. +func (f *FileTaskStep) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageDependencies": + err = unpopulate(val, "BaseImageDependencies", &f.BaseImageDependencies) + delete(rawMsg, key) + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &f.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &f.ContextPath) + delete(rawMsg, key) + case "taskFilePath": + err = unpopulate(val, "TaskFilePath", &f.TaskFilePath) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &f.Values) + delete(rawMsg, key) + case "valuesFilePath": + err = unpopulate(val, "ValuesFilePath", &f.ValuesFilePath) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileTaskStepUpdateParameters. +func (f FileTaskStepUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contextAccessToken", f.ContextAccessToken) + populate(objectMap, "contextPath", f.ContextPath) + populate(objectMap, "taskFilePath", f.TaskFilePath) + objectMap["type"] = StepTypeFileTask + populate(objectMap, "values", f.Values) + populate(objectMap, "valuesFilePath", f.ValuesFilePath) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileTaskStepUpdateParameters. +func (f *FileTaskStepUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &f.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &f.ContextPath) + delete(rawMsg, key) + case "taskFilePath": + err = unpopulate(val, "TaskFilePath", &f.TaskFilePath) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &f.Values) + delete(rawMsg, key) + case "valuesFilePath": + err = unpopulate(val, "ValuesFilePath", &f.ValuesFilePath) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GenerateCredentialsParameters. +func (g GenerateCredentialsParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiry", g.Expiry) + populate(objectMap, "name", g.Name) + populate(objectMap, "tokenId", g.TokenID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerateCredentialsParameters. +func (g *GenerateCredentialsParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiry": + err = unpopulateDateTimeRFC3339(val, "Expiry", &g.Expiry) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "tokenId": + err = unpopulate(val, "TokenID", &g.TokenID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GenerateCredentialsResult. +func (g GenerateCredentialsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "passwords", g.Passwords) + populate(objectMap, "username", g.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerateCredentialsResult. +func (g *GenerateCredentialsResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "passwords": + err = unpopulate(val, "Passwords", &g.Passwords) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &g.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IPRule. +func (i IPRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", i.Action) + populate(objectMap, "value", i.IPAddressOrRange) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPRule. +func (i *IPRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &i.Action) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "IPAddressOrRange", &i.IPAddressOrRange) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IdentityProperties. +func (i IdentityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", i.PrincipalID) + populate(objectMap, "tenantId", i.TenantID) + populate(objectMap, "type", i.Type) + populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IdentityProperties. +func (i *IdentityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &i.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &i.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &i.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImageDescriptor. +func (i ImageDescriptor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "digest", i.Digest) + populate(objectMap, "registry", i.Registry) + populate(objectMap, "repository", i.Repository) + populate(objectMap, "tag", i.Tag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageDescriptor. +func (i *ImageDescriptor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "digest": + err = unpopulate(val, "Digest", &i.Digest) + delete(rawMsg, key) + case "registry": + err = unpopulate(val, "Registry", &i.Registry) + delete(rawMsg, key) + case "repository": + err = unpopulate(val, "Repository", &i.Repository) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &i.Tag) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImageUpdateTrigger. +func (i ImageUpdateTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", i.ID) + populate(objectMap, "images", i.Images) + populateDateTimeRFC3339(objectMap, "timestamp", i.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageUpdateTrigger. +func (i *ImageUpdateTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "images": + err = unpopulate(val, "Images", &i.Images) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &i.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImportImageParameters. +func (i ImportImageParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mode", i.Mode) + populate(objectMap, "source", i.Source) + populate(objectMap, "targetTags", i.TargetTags) + populate(objectMap, "untaggedTargetRepositories", i.UntaggedTargetRepositories) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImportImageParameters. +func (i *ImportImageParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mode": + err = unpopulate(val, "Mode", &i.Mode) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &i.Source) + delete(rawMsg, key) + case "targetTags": + err = unpopulate(val, "TargetTags", &i.TargetTags) + delete(rawMsg, key) + case "untaggedTargetRepositories": + err = unpopulate(val, "UntaggedTargetRepositories", &i.UntaggedTargetRepositories) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImportSource. +func (i ImportSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "credentials", i.Credentials) + populate(objectMap, "registryUri", i.RegistryURI) + populate(objectMap, "resourceId", i.ResourceID) + populate(objectMap, "sourceImage", i.SourceImage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImportSource. +func (i *ImportSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "credentials": + err = unpopulate(val, "Credentials", &i.Credentials) + delete(rawMsg, key) + case "registryUri": + err = unpopulate(val, "RegistryURI", &i.RegistryURI) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &i.ResourceID) + delete(rawMsg, key) + case "sourceImage": + err = unpopulate(val, "SourceImage", &i.SourceImage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImportSourceCredentials. +func (i ImportSourceCredentials) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "password", i.Password) + populate(objectMap, "username", i.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImportSourceCredentials. +func (i *ImportSourceCredentials) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "password": + err = unpopulate(val, "Password", &i.Password) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &i.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVaultProperties. +func (k KeyVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", k.Identity) + populate(objectMap, "keyIdentifier", k.KeyIdentifier) + populate(objectMap, "keyRotationEnabled", k.KeyRotationEnabled) + populateDateTimeRFC3339(objectMap, "lastKeyRotationTimestamp", k.LastKeyRotationTimestamp) + populate(objectMap, "versionedKeyIdentifier", k.VersionedKeyIdentifier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultProperties. +func (k *KeyVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &k.Identity) + delete(rawMsg, key) + case "keyIdentifier": + err = unpopulate(val, "KeyIdentifier", &k.KeyIdentifier) + delete(rawMsg, key) + case "keyRotationEnabled": + err = unpopulate(val, "KeyRotationEnabled", &k.KeyRotationEnabled) + delete(rawMsg, key) + case "lastKeyRotationTimestamp": + err = unpopulateDateTimeRFC3339(val, "LastKeyRotationTimestamp", &k.LastKeyRotationTimestamp) + delete(rawMsg, key) + case "versionedKeyIdentifier": + err = unpopulate(val, "VersionedKeyIdentifier", &k.VersionedKeyIdentifier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkRuleSet. +func (n NetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultAction", n.DefaultAction) + populate(objectMap, "ipRules", n.IPRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkRuleSet. +func (n *NetworkRuleSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "defaultAction": + err = unpopulate(val, "DefaultAction", &n.DefaultAction) + delete(rawMsg, key) + case "ipRules": + err = unpopulate(val, "IPRules", &n.IPRules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDefinition. +func (o OperationDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + populate(objectMap, "properties", o.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDefinition. +func (o *OperationDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplayDefinition. +func (o OperationDisplayDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplayDefinition. +func (o *OperationDisplayDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationLogSpecificationDefinition. +func (o OperationLogSpecificationDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobDuration", o.BlobDuration) + populate(objectMap, "displayName", o.DisplayName) + populate(objectMap, "name", o.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationLogSpecificationDefinition. +func (o *OperationLogSpecificationDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blobDuration": + err = unpopulate(val, "BlobDuration", &o.BlobDuration) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &o.DisplayName) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationMetricSpecificationDefinition. +func (o OperationMetricSpecificationDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationType", o.AggregationType) + populate(objectMap, "displayDescription", o.DisplayDescription) + populate(objectMap, "displayName", o.DisplayName) + populate(objectMap, "internalMetricName", o.InternalMetricName) + populate(objectMap, "name", o.Name) + populate(objectMap, "unit", o.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationMetricSpecificationDefinition. +func (o *OperationMetricSpecificationDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aggregationType": + err = unpopulate(val, "AggregationType", &o.AggregationType) + delete(rawMsg, key) + case "displayDescription": + err = unpopulate(val, "DisplayDescription", &o.DisplayDescription) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &o.DisplayName) + delete(rawMsg, key) + case "internalMetricName": + err = unpopulate(val, "InternalMetricName", &o.InternalMetricName) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &o.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationPropertiesDefinition. +func (o OperationPropertiesDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceSpecification", o.ServiceSpecification) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationPropertiesDefinition. +func (o *OperationPropertiesDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "serviceSpecification": + err = unpopulate(val, "ServiceSpecification", &o.ServiceSpecification) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationServiceSpecificationDefinition. +func (o OperationServiceSpecificationDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "logSpecifications", o.LogSpecifications) + populate(objectMap, "metricSpecifications", o.MetricSpecifications) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationServiceSpecificationDefinition. +func (o *OperationServiceSpecificationDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "logSpecifications": + err = unpopulate(val, "LogSpecifications", &o.LogSpecifications) + delete(rawMsg, key) + case "metricSpecifications": + err = unpopulate(val, "MetricSpecifications", &o.MetricSpecifications) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OverrideTaskStepProperties. +func (o OverrideTaskStepProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "arguments", o.Arguments) + populate(objectMap, "contextPath", o.ContextPath) + populate(objectMap, "file", o.File) + populate(objectMap, "target", o.Target) + populate(objectMap, "updateTriggerToken", o.UpdateTriggerToken) + populate(objectMap, "values", o.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OverrideTaskStepProperties. +func (o *OverrideTaskStepProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "arguments": + err = unpopulate(val, "Arguments", &o.Arguments) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &o.ContextPath) + delete(rawMsg, key) + case "file": + err = unpopulate(val, "File", &o.File) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &o.Target) + delete(rawMsg, key) + case "updateTriggerToken": + err = unpopulate(val, "UpdateTriggerToken", &o.UpdateTriggerToken) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &o.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PlatformProperties. +func (p PlatformProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "architecture", p.Architecture) + populate(objectMap, "os", p.OS) + populate(objectMap, "variant", p.Variant) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PlatformProperties. +func (p *PlatformProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "architecture": + err = unpopulate(val, "Architecture", &p.Architecture) + delete(rawMsg, key) + case "os": + err = unpopulate(val, "OS", &p.OS) + delete(rawMsg, key) + case "variant": + err = unpopulate(val, "Variant", &p.Variant) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PlatformUpdateParameters. +func (p PlatformUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "architecture", p.Architecture) + populate(objectMap, "os", p.OS) + populate(objectMap, "variant", p.Variant) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PlatformUpdateParameters. +func (p *PlatformUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "architecture": + err = unpopulate(val, "Architecture", &p.Architecture) + delete(rawMsg, key) + case "os": + err = unpopulate(val, "OS", &p.OS) + delete(rawMsg, key) + case "variant": + err = unpopulate(val, "Variant", &p.Variant) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Policies. +func (p Policies) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "exportPolicy", p.ExportPolicy) + populate(objectMap, "quarantinePolicy", p.QuarantinePolicy) + populate(objectMap, "retentionPolicy", p.RetentionPolicy) + populate(objectMap, "trustPolicy", p.TrustPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Policies. +func (p *Policies) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "exportPolicy": + err = unpopulate(val, "ExportPolicy", &p.ExportPolicy) + delete(rawMsg, key) + case "quarantinePolicy": + err = unpopulate(val, "QuarantinePolicy", &p.QuarantinePolicy) + delete(rawMsg, key) + case "retentionPolicy": + err = unpopulate(val, "RetentionPolicy", &p.RetentionPolicy) + delete(rawMsg, key) + case "trustPolicy": + err = unpopulate(val, "TrustPolicy", &p.TrustPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpoint. +func (p *PrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnection. +func (p *PrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionListResult. +func (p *PrivateEndpointConnectionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionProperties. +func (p *PrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResource. +func (p *PrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceListResult. +func (p *PrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceProperties. +func (p *PrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupId": + err = unpopulate(val, "GroupID", &p.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &p.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &p.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionState. +func (p PrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionsRequired", p.ActionsRequired) + populate(objectMap, "description", p.Description) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionState. +func (p *PrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionsRequired": + err = unpopulate(val, "ActionsRequired", &p.ActionsRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuarantinePolicy. +func (q QuarantinePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", q.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuarantinePolicy. +func (q *QuarantinePolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "status": + err = unpopulate(val, "Status", &q.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegenerateCredentialParameters. +func (r RegenerateCredentialParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegenerateCredentialParameters. +func (r *RegenerateCredentialParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Registry. +func (r Registry) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "identity", r.Identity) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "sku", r.SKU) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Registry. +func (r *Registry) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &r.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &r.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryListCredentialsResult. +func (r RegistryListCredentialsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "passwords", r.Passwords) + populate(objectMap, "username", r.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryListCredentialsResult. +func (r *RegistryListCredentialsResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "passwords": + err = unpopulate(val, "Passwords", &r.Passwords) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &r.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryListResult. +func (r RegistryListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryListResult. +func (r *RegistryListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryNameCheckRequest. +func (r RegistryNameCheckRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + objectMap["type"] = "Microsoft.ContainerRegistry/registries" + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryNameCheckRequest. +func (r *RegistryNameCheckRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryNameStatus. +func (r RegistryNameStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", r.Message) + populate(objectMap, "nameAvailable", r.NameAvailable) + populate(objectMap, "reason", r.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryNameStatus. +func (r *RegistryNameStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &r.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &r.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &r.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryPassword. +func (r RegistryPassword) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryPassword. +func (r *RegistryPassword) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryProperties. +func (r RegistryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminUserEnabled", r.AdminUserEnabled) + populateDateTimeRFC3339(objectMap, "creationDate", r.CreationDate) + populate(objectMap, "dataEndpointEnabled", r.DataEndpointEnabled) + populate(objectMap, "dataEndpointHostNames", r.DataEndpointHostNames) + populate(objectMap, "encryption", r.Encryption) + populate(objectMap, "loginServer", r.LoginServer) + populate(objectMap, "networkRuleBypassOptions", r.NetworkRuleBypassOptions) + populate(objectMap, "networkRuleSet", r.NetworkRuleSet) + populate(objectMap, "policies", r.Policies) + populate(objectMap, "privateEndpointConnections", r.PrivateEndpointConnections) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "publicNetworkAccess", r.PublicNetworkAccess) + populate(objectMap, "status", r.Status) + populate(objectMap, "zoneRedundancy", r.ZoneRedundancy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryProperties. +func (r *RegistryProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adminUserEnabled": + err = unpopulate(val, "AdminUserEnabled", &r.AdminUserEnabled) + delete(rawMsg, key) + case "creationDate": + err = unpopulateDateTimeRFC3339(val, "CreationDate", &r.CreationDate) + delete(rawMsg, key) + case "dataEndpointEnabled": + err = unpopulate(val, "DataEndpointEnabled", &r.DataEndpointEnabled) + delete(rawMsg, key) + case "dataEndpointHostNames": + err = unpopulate(val, "DataEndpointHostNames", &r.DataEndpointHostNames) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &r.Encryption) + delete(rawMsg, key) + case "loginServer": + err = unpopulate(val, "LoginServer", &r.LoginServer) + delete(rawMsg, key) + case "networkRuleBypassOptions": + err = unpopulate(val, "NetworkRuleBypassOptions", &r.NetworkRuleBypassOptions) + delete(rawMsg, key) + case "networkRuleSet": + err = unpopulate(val, "NetworkRuleSet", &r.NetworkRuleSet) + delete(rawMsg, key) + case "policies": + err = unpopulate(val, "Policies", &r.Policies) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &r.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &r.PublicNetworkAccess) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + case "zoneRedundancy": + err = unpopulate(val, "ZoneRedundancy", &r.ZoneRedundancy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryPropertiesUpdateParameters. +func (r RegistryPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminUserEnabled", r.AdminUserEnabled) + populate(objectMap, "dataEndpointEnabled", r.DataEndpointEnabled) + populate(objectMap, "encryption", r.Encryption) + populate(objectMap, "networkRuleBypassOptions", r.NetworkRuleBypassOptions) + populate(objectMap, "networkRuleSet", r.NetworkRuleSet) + populate(objectMap, "policies", r.Policies) + populate(objectMap, "publicNetworkAccess", r.PublicNetworkAccess) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryPropertiesUpdateParameters. +func (r *RegistryPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adminUserEnabled": + err = unpopulate(val, "AdminUserEnabled", &r.AdminUserEnabled) + delete(rawMsg, key) + case "dataEndpointEnabled": + err = unpopulate(val, "DataEndpointEnabled", &r.DataEndpointEnabled) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &r.Encryption) + delete(rawMsg, key) + case "networkRuleBypassOptions": + err = unpopulate(val, "NetworkRuleBypassOptions", &r.NetworkRuleBypassOptions) + delete(rawMsg, key) + case "networkRuleSet": + err = unpopulate(val, "NetworkRuleSet", &r.NetworkRuleSet) + delete(rawMsg, key) + case "policies": + err = unpopulate(val, "Policies", &r.Policies) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &r.PublicNetworkAccess) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryUpdateParameters. +func (r RegistryUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", r.Identity) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "sku", r.SKU) + populate(objectMap, "tags", r.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryUpdateParameters. +func (r *RegistryUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &r.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &r.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryUsage. +func (r RegistryUsage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentValue", r.CurrentValue) + populate(objectMap, "limit", r.Limit) + populate(objectMap, "name", r.Name) + populate(objectMap, "unit", r.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryUsage. +func (r *RegistryUsage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentValue": + err = unpopulate(val, "CurrentValue", &r.CurrentValue) + delete(rawMsg, key) + case "limit": + err = unpopulate(val, "Limit", &r.Limit) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &r.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegistryUsageListResult. +func (r RegistryUsageListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegistryUsageListResult. +func (r *RegistryUsageListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Replication. +func (r Replication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Replication. +func (r *Replication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicationListResult. +func (r ReplicationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicationListResult. +func (r *ReplicationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicationProperties. +func (r ReplicationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "regionEndpointEnabled", r.RegionEndpointEnabled) + populate(objectMap, "status", r.Status) + populate(objectMap, "zoneRedundancy", r.ZoneRedundancy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicationProperties. +func (r *ReplicationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "regionEndpointEnabled": + err = unpopulate(val, "RegionEndpointEnabled", &r.RegionEndpointEnabled) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + case "zoneRedundancy": + err = unpopulate(val, "ZoneRedundancy", &r.ZoneRedundancy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicationUpdateParameters. +func (r ReplicationUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "tags", r.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicationUpdateParameters. +func (r *ReplicationUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicationUpdateParametersProperties. +func (r ReplicationUpdateParametersProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "regionEndpointEnabled", r.RegionEndpointEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicationUpdateParametersProperties. +func (r *ReplicationUpdateParametersProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "regionEndpointEnabled": + err = unpopulate(val, "RegionEndpointEnabled", &r.RegionEndpointEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Request. +func (r Request) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addr", r.Addr) + populate(objectMap, "host", r.Host) + populate(objectMap, "id", r.ID) + populate(objectMap, "method", r.Method) + populate(objectMap, "useragent", r.Useragent) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Request. +func (r *Request) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addr": + err = unpopulate(val, "Addr", &r.Addr) + delete(rawMsg, key) + case "host": + err = unpopulate(val, "Host", &r.Host) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "method": + err = unpopulate(val, "Method", &r.Method) + delete(rawMsg, key) + case "useragent": + err = unpopulate(val, "Useragent", &r.Useragent) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RetentionPolicy. +func (r RetentionPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "days", r.Days) + populateDateTimeRFC3339(objectMap, "lastUpdatedTime", r.LastUpdatedTime) + populate(objectMap, "status", r.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RetentionPolicy. +func (r *RetentionPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "days": + err = unpopulate(val, "Days", &r.Days) + delete(rawMsg, key) + case "lastUpdatedTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdatedTime", &r.LastUpdatedTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Run. +func (r Run) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Run. +func (r *Run) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RunFilter. +func (r RunFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentPoolName", r.AgentPoolName) + populateDateTimeRFC3339(objectMap, "createTime", r.CreateTime) + populateDateTimeRFC3339(objectMap, "finishTime", r.FinishTime) + populate(objectMap, "isArchiveEnabled", r.IsArchiveEnabled) + populate(objectMap, "outputImageManifests", r.OutputImageManifests) + populate(objectMap, "runId", r.RunID) + populate(objectMap, "runType", r.RunType) + populate(objectMap, "status", r.Status) + populate(objectMap, "taskName", r.TaskName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunFilter. +func (r *RunFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &r.AgentPoolName) + delete(rawMsg, key) + case "createTime": + err = unpopulateDateTimeRFC3339(val, "CreateTime", &r.CreateTime) + delete(rawMsg, key) + case "finishTime": + err = unpopulateDateTimeRFC3339(val, "FinishTime", &r.FinishTime) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &r.IsArchiveEnabled) + delete(rawMsg, key) + case "outputImageManifests": + err = unpopulate(val, "OutputImageManifests", &r.OutputImageManifests) + delete(rawMsg, key) + case "runId": + err = unpopulate(val, "RunID", &r.RunID) + delete(rawMsg, key) + case "runType": + err = unpopulate(val, "RunType", &r.RunType) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + case "taskName": + err = unpopulate(val, "TaskName", &r.TaskName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RunGetLogResult. +func (r RunGetLogResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "logArtifactLink", r.LogArtifactLink) + populate(objectMap, "logLink", r.LogLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunGetLogResult. +func (r *RunGetLogResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "logArtifactLink": + err = unpopulate(val, "LogArtifactLink", &r.LogArtifactLink) + delete(rawMsg, key) + case "logLink": + err = unpopulate(val, "LogLink", &r.LogLink) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RunListResult. +func (r RunListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunListResult. +func (r *RunListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RunProperties. +func (r RunProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentConfiguration", r.AgentConfiguration) + populate(objectMap, "agentPoolName", r.AgentPoolName) + populateDateTimeRFC3339(objectMap, "createTime", r.CreateTime) + populate(objectMap, "customRegistries", r.CustomRegistries) + populateDateTimeRFC3339(objectMap, "finishTime", r.FinishTime) + populate(objectMap, "imageUpdateTrigger", r.ImageUpdateTrigger) + populate(objectMap, "isArchiveEnabled", r.IsArchiveEnabled) + populateDateTimeRFC3339(objectMap, "lastUpdatedTime", r.LastUpdatedTime) + populate(objectMap, "logArtifact", r.LogArtifact) + populate(objectMap, "outputImages", r.OutputImages) + populate(objectMap, "platform", r.Platform) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "runErrorMessage", r.RunErrorMessage) + populate(objectMap, "runId", r.RunID) + populate(objectMap, "runType", r.RunType) + populate(objectMap, "sourceRegistryAuth", r.SourceRegistryAuth) + populate(objectMap, "sourceTrigger", r.SourceTrigger) + populateDateTimeRFC3339(objectMap, "startTime", r.StartTime) + populate(objectMap, "status", r.Status) + populate(objectMap, "task", r.Task) + populate(objectMap, "timerTrigger", r.TimerTrigger) + populate(objectMap, "updateTriggerToken", r.UpdateTriggerToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunProperties. +func (r *RunProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentConfiguration": + err = unpopulate(val, "AgentConfiguration", &r.AgentConfiguration) + delete(rawMsg, key) + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &r.AgentPoolName) + delete(rawMsg, key) + case "createTime": + err = unpopulateDateTimeRFC3339(val, "CreateTime", &r.CreateTime) + delete(rawMsg, key) + case "customRegistries": + err = unpopulate(val, "CustomRegistries", &r.CustomRegistries) + delete(rawMsg, key) + case "finishTime": + err = unpopulateDateTimeRFC3339(val, "FinishTime", &r.FinishTime) + delete(rawMsg, key) + case "imageUpdateTrigger": + err = unpopulate(val, "ImageUpdateTrigger", &r.ImageUpdateTrigger) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &r.IsArchiveEnabled) + delete(rawMsg, key) + case "lastUpdatedTime": + err = unpopulateDateTimeRFC3339(val, "LastUpdatedTime", &r.LastUpdatedTime) + delete(rawMsg, key) + case "logArtifact": + err = unpopulate(val, "LogArtifact", &r.LogArtifact) + delete(rawMsg, key) + case "outputImages": + err = unpopulate(val, "OutputImages", &r.OutputImages) + delete(rawMsg, key) + case "platform": + err = unpopulate(val, "Platform", &r.Platform) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "runErrorMessage": + err = unpopulate(val, "RunErrorMessage", &r.RunErrorMessage) + delete(rawMsg, key) + case "runId": + err = unpopulate(val, "RunID", &r.RunID) + delete(rawMsg, key) + case "runType": + err = unpopulate(val, "RunType", &r.RunType) + delete(rawMsg, key) + case "sourceRegistryAuth": + err = unpopulate(val, "SourceRegistryAuth", &r.SourceRegistryAuth) + delete(rawMsg, key) + case "sourceTrigger": + err = unpopulate(val, "SourceTrigger", &r.SourceTrigger) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &r.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + case "task": + err = unpopulate(val, "Task", &r.Task) + delete(rawMsg, key) + case "timerTrigger": + err = unpopulate(val, "TimerTrigger", &r.TimerTrigger) + delete(rawMsg, key) + case "updateTriggerToken": + err = unpopulate(val, "UpdateTriggerToken", &r.UpdateTriggerToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RunRequest. +func (r RunRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentPoolName", r.AgentPoolName) + populate(objectMap, "isArchiveEnabled", r.IsArchiveEnabled) + populate(objectMap, "logTemplate", r.LogTemplate) + objectMap["type"] = r.Type + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunRequest. +func (r *RunRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &r.AgentPoolName) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &r.IsArchiveEnabled) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &r.LogTemplate) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RunUpdateParameters. +func (r RunUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isArchiveEnabled", r.IsArchiveEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RunUpdateParameters. +func (r *RunUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &r.IsArchiveEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScopeMap. +func (s ScopeMap) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScopeMap. +func (s *ScopeMap) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScopeMapListResult. +func (s ScopeMapListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScopeMapListResult. +func (s *ScopeMapListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScopeMapProperties. +func (s ScopeMapProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", s.Actions) + populateDateTimeRFC3339(objectMap, "creationDate", s.CreationDate) + populate(objectMap, "description", s.Description) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScopeMapProperties. +func (s *ScopeMapProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &s.Actions) + delete(rawMsg, key) + case "creationDate": + err = unpopulateDateTimeRFC3339(val, "CreationDate", &s.CreationDate) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScopeMapPropertiesUpdateParameters. +func (s ScopeMapPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", s.Actions) + populate(objectMap, "description", s.Description) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScopeMapPropertiesUpdateParameters. +func (s *ScopeMapPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &s.Actions) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScopeMapUpdateParameters. +func (s ScopeMapUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScopeMapUpdateParameters. +func (s *ScopeMapUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretObject. +func (s SecretObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", s.Type) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretObject. +func (s *SecretObject) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SetValue. +func (s SetValue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isSecret", s.IsSecret) + populate(objectMap, "name", s.Name) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SetValue. +func (s *SetValue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isSecret": + err = unpopulate(val, "IsSecret", &s.IsSecret) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Source. +func (s Source) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addr", s.Addr) + populate(objectMap, "instanceID", s.InstanceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Source. +func (s *Source) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addr": + err = unpopulate(val, "Addr", &s.Addr) + delete(rawMsg, key) + case "instanceID": + err = unpopulate(val, "InstanceID", &s.InstanceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceProperties. +func (s SourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "branch", s.Branch) + populate(objectMap, "repositoryUrl", s.RepositoryURL) + populate(objectMap, "sourceControlAuthProperties", s.SourceControlAuthProperties) + populate(objectMap, "sourceControlType", s.SourceControlType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceProperties. +func (s *SourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "branch": + err = unpopulate(val, "Branch", &s.Branch) + delete(rawMsg, key) + case "repositoryUrl": + err = unpopulate(val, "RepositoryURL", &s.RepositoryURL) + delete(rawMsg, key) + case "sourceControlAuthProperties": + err = unpopulate(val, "SourceControlAuthProperties", &s.SourceControlAuthProperties) + delete(rawMsg, key) + case "sourceControlType": + err = unpopulate(val, "SourceControlType", &s.SourceControlType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceRegistryCredentials. +func (s SourceRegistryCredentials) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "loginMode", s.LoginMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceRegistryCredentials. +func (s *SourceRegistryCredentials) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "loginMode": + err = unpopulate(val, "LoginMode", &s.LoginMode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceTrigger. +func (s SourceTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "sourceRepository", s.SourceRepository) + populate(objectMap, "sourceTriggerEvents", s.SourceTriggerEvents) + populate(objectMap, "status", s.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceTrigger. +func (s *SourceTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "sourceRepository": + err = unpopulate(val, "SourceRepository", &s.SourceRepository) + delete(rawMsg, key) + case "sourceTriggerEvents": + err = unpopulate(val, "SourceTriggerEvents", &s.SourceTriggerEvents) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &s.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceTriggerDescriptor. +func (s SourceTriggerDescriptor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "branchName", s.BranchName) + populate(objectMap, "commitId", s.CommitID) + populate(objectMap, "eventType", s.EventType) + populate(objectMap, "id", s.ID) + populate(objectMap, "providerType", s.ProviderType) + populate(objectMap, "pullRequestId", s.PullRequestID) + populate(objectMap, "repositoryUrl", s.RepositoryURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceTriggerDescriptor. +func (s *SourceTriggerDescriptor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "branchName": + err = unpopulate(val, "BranchName", &s.BranchName) + delete(rawMsg, key) + case "commitId": + err = unpopulate(val, "CommitID", &s.CommitID) + delete(rawMsg, key) + case "eventType": + err = unpopulate(val, "EventType", &s.EventType) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "providerType": + err = unpopulate(val, "ProviderType", &s.ProviderType) + delete(rawMsg, key) + case "pullRequestId": + err = unpopulate(val, "PullRequestID", &s.PullRequestID) + delete(rawMsg, key) + case "repositoryUrl": + err = unpopulate(val, "RepositoryURL", &s.RepositoryURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceTriggerUpdateParameters. +func (s SourceTriggerUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "sourceRepository", s.SourceRepository) + populate(objectMap, "sourceTriggerEvents", s.SourceTriggerEvents) + populate(objectMap, "status", s.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceTriggerUpdateParameters. +func (s *SourceTriggerUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "sourceRepository": + err = unpopulate(val, "SourceRepository", &s.SourceRepository) + delete(rawMsg, key) + case "sourceTriggerEvents": + err = unpopulate(val, "SourceTriggerEvents", &s.SourceTriggerEvents) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &s.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceUpdateParameters. +func (s SourceUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "branch", s.Branch) + populate(objectMap, "repositoryUrl", s.RepositoryURL) + populate(objectMap, "sourceControlAuthProperties", s.SourceControlAuthProperties) + populate(objectMap, "sourceControlType", s.SourceControlType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceUpdateParameters. +func (s *SourceUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "branch": + err = unpopulate(val, "Branch", &s.Branch) + delete(rawMsg, key) + case "repositoryUrl": + err = unpopulate(val, "RepositoryURL", &s.RepositoryURL) + delete(rawMsg, key) + case "sourceControlAuthProperties": + err = unpopulate(val, "SourceControlAuthProperties", &s.SourceControlAuthProperties) + delete(rawMsg, key) + case "sourceControlType": + err = unpopulate(val, "SourceControlType", &s.SourceControlType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceUploadDefinition. +func (s SourceUploadDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "relativePath", s.RelativePath) + populate(objectMap, "uploadUrl", s.UploadURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceUploadDefinition. +func (s *SourceUploadDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "relativePath": + err = unpopulate(val, "RelativePath", &s.RelativePath) + delete(rawMsg, key) + case "uploadUrl": + err = unpopulate(val, "UploadURL", &s.UploadURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Status. +func (s Status) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayStatus", s.DisplayStatus) + populate(objectMap, "message", s.Message) + populateDateTimeRFC3339(objectMap, "timestamp", s.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Status. +func (s *Status) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayStatus": + err = unpopulate(val, "DisplayStatus", &s.DisplayStatus) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &s.Message) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &s.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateDateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateDateTimeRFC3339(val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateDateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Target. +func (t Target) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "digest", t.Digest) + populate(objectMap, "length", t.Length) + populate(objectMap, "mediaType", t.MediaType) + populate(objectMap, "name", t.Name) + populate(objectMap, "repository", t.Repository) + populate(objectMap, "size", t.Size) + populate(objectMap, "tag", t.Tag) + populate(objectMap, "url", t.URL) + populate(objectMap, "version", t.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Target. +func (t *Target) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "digest": + err = unpopulate(val, "Digest", &t.Digest) + delete(rawMsg, key) + case "length": + err = unpopulate(val, "Length", &t.Length) + delete(rawMsg, key) + case "mediaType": + err = unpopulate(val, "MediaType", &t.MediaType) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "repository": + err = unpopulate(val, "Repository", &t.Repository) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &t.Size) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &t.Tag) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &t.URL) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &t.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Task. +func (t Task) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "identity", t.Identity) + populate(objectMap, "location", t.Location) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "tags", t.Tags) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Task. +func (t *Task) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &t.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskListResult. +func (t TaskListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskListResult. +func (t *TaskListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskProperties. +func (t TaskProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentConfiguration", t.AgentConfiguration) + populate(objectMap, "agentPoolName", t.AgentPoolName) + populateDateTimeRFC3339(objectMap, "creationDate", t.CreationDate) + populate(objectMap, "credentials", t.Credentials) + populate(objectMap, "isSystemTask", t.IsSystemTask) + populate(objectMap, "logTemplate", t.LogTemplate) + populate(objectMap, "platform", t.Platform) + populate(objectMap, "provisioningState", t.ProvisioningState) + populate(objectMap, "status", t.Status) + populate(objectMap, "step", t.Step) + populate(objectMap, "timeout", t.Timeout) + populate(objectMap, "trigger", t.Trigger) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskProperties. +func (t *TaskProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentConfiguration": + err = unpopulate(val, "AgentConfiguration", &t.AgentConfiguration) + delete(rawMsg, key) + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &t.AgentPoolName) + delete(rawMsg, key) + case "creationDate": + err = unpopulateDateTimeRFC3339(val, "CreationDate", &t.CreationDate) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &t.Credentials) + delete(rawMsg, key) + case "isSystemTask": + err = unpopulate(val, "IsSystemTask", &t.IsSystemTask) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &t.LogTemplate) + delete(rawMsg, key) + case "platform": + err = unpopulate(val, "Platform", &t.Platform) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &t.ProvisioningState) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + case "step": + t.Step, err = unmarshalTaskStepPropertiesClassification(val) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &t.Timeout) + delete(rawMsg, key) + case "trigger": + err = unpopulate(val, "Trigger", &t.Trigger) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskPropertiesUpdateParameters. +func (t TaskPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentConfiguration", t.AgentConfiguration) + populate(objectMap, "agentPoolName", t.AgentPoolName) + populate(objectMap, "credentials", t.Credentials) + populate(objectMap, "logTemplate", t.LogTemplate) + populate(objectMap, "platform", t.Platform) + populate(objectMap, "status", t.Status) + populate(objectMap, "step", t.Step) + populate(objectMap, "timeout", t.Timeout) + populate(objectMap, "trigger", t.Trigger) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskPropertiesUpdateParameters. +func (t *TaskPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentConfiguration": + err = unpopulate(val, "AgentConfiguration", &t.AgentConfiguration) + delete(rawMsg, key) + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &t.AgentPoolName) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &t.Credentials) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &t.LogTemplate) + delete(rawMsg, key) + case "platform": + err = unpopulate(val, "Platform", &t.Platform) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + case "step": + t.Step, err = unmarshalTaskStepUpdateParametersClassification(val) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &t.Timeout) + delete(rawMsg, key) + case "trigger": + err = unpopulate(val, "Trigger", &t.Trigger) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskRun. +func (t TaskRun) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "identity", t.Identity) + populate(objectMap, "location", t.Location) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskRun. +func (t *TaskRun) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &t.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskRunListResult. +func (t TaskRunListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskRunListResult. +func (t *TaskRunListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskRunProperties. +func (t TaskRunProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "forceUpdateTag", t.ForceUpdateTag) + populate(objectMap, "provisioningState", t.ProvisioningState) + populate(objectMap, "runRequest", t.RunRequest) + populate(objectMap, "runResult", t.RunResult) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskRunProperties. +func (t *TaskRunProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &t.ForceUpdateTag) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &t.ProvisioningState) + delete(rawMsg, key) + case "runRequest": + t.RunRequest, err = unmarshalRunRequestClassification(val) + delete(rawMsg, key) + case "runResult": + err = unpopulate(val, "RunResult", &t.RunResult) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskRunPropertiesUpdateParameters. +func (t TaskRunPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "forceUpdateTag", t.ForceUpdateTag) + populate(objectMap, "runRequest", t.RunRequest) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskRunPropertiesUpdateParameters. +func (t *TaskRunPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &t.ForceUpdateTag) + delete(rawMsg, key) + case "runRequest": + t.RunRequest, err = unmarshalRunRequestClassification(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskRunRequest. +func (t TaskRunRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentPoolName", t.AgentPoolName) + populate(objectMap, "isArchiveEnabled", t.IsArchiveEnabled) + populate(objectMap, "logTemplate", t.LogTemplate) + populate(objectMap, "overrideTaskStepProperties", t.OverrideTaskStepProperties) + populate(objectMap, "taskId", t.TaskID) + objectMap["type"] = "TaskRunRequest" + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskRunRequest. +func (t *TaskRunRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentPoolName": + err = unpopulate(val, "AgentPoolName", &t.AgentPoolName) + delete(rawMsg, key) + case "isArchiveEnabled": + err = unpopulate(val, "IsArchiveEnabled", &t.IsArchiveEnabled) + delete(rawMsg, key) + case "logTemplate": + err = unpopulate(val, "LogTemplate", &t.LogTemplate) + delete(rawMsg, key) + case "overrideTaskStepProperties": + err = unpopulate(val, "OverrideTaskStepProperties", &t.OverrideTaskStepProperties) + delete(rawMsg, key) + case "taskId": + err = unpopulate(val, "TaskID", &t.TaskID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskRunUpdateParameters. +func (t TaskRunUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", t.Identity) + populate(objectMap, "location", t.Location) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "tags", t.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskRunUpdateParameters. +func (t *TaskRunUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &t.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskStepProperties. +func (t TaskStepProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageDependencies", t.BaseImageDependencies) + populate(objectMap, "contextAccessToken", t.ContextAccessToken) + populate(objectMap, "contextPath", t.ContextPath) + objectMap["type"] = t.Type + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskStepProperties. +func (t *TaskStepProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageDependencies": + err = unpopulate(val, "BaseImageDependencies", &t.BaseImageDependencies) + delete(rawMsg, key) + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &t.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &t.ContextPath) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskStepUpdateParameters. +func (t TaskStepUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contextAccessToken", t.ContextAccessToken) + populate(objectMap, "contextPath", t.ContextPath) + objectMap["type"] = t.Type + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskStepUpdateParameters. +func (t *TaskStepUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contextAccessToken": + err = unpopulate(val, "ContextAccessToken", &t.ContextAccessToken) + delete(rawMsg, key) + case "contextPath": + err = unpopulate(val, "ContextPath", &t.ContextPath) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TaskUpdateParameters. +func (t TaskUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", t.Identity) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "tags", t.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TaskUpdateParameters. +func (t *TaskUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &t.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TimerTrigger. +func (t TimerTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", t.Name) + populate(objectMap, "schedule", t.Schedule) + populate(objectMap, "status", t.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TimerTrigger. +func (t *TimerTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &t.Schedule) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TimerTriggerDescriptor. +func (t TimerTriggerDescriptor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "scheduleOccurrence", t.ScheduleOccurrence) + populate(objectMap, "timerTriggerName", t.TimerTriggerName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TimerTriggerDescriptor. +func (t *TimerTriggerDescriptor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "scheduleOccurrence": + err = unpopulate(val, "ScheduleOccurrence", &t.ScheduleOccurrence) + delete(rawMsg, key) + case "timerTriggerName": + err = unpopulate(val, "TimerTriggerName", &t.TimerTriggerName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TimerTriggerUpdateParameters. +func (t TimerTriggerUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", t.Name) + populate(objectMap, "schedule", t.Schedule) + populate(objectMap, "status", t.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TimerTriggerUpdateParameters. +func (t *TimerTriggerUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &t.Schedule) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Token. +func (t Token) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Token. +func (t *Token) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenCertificate. +func (t TokenCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encodedPemCertificate", t.EncodedPemCertificate) + populateDateTimeRFC3339(objectMap, "expiry", t.Expiry) + populate(objectMap, "name", t.Name) + populate(objectMap, "thumbprint", t.Thumbprint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenCertificate. +func (t *TokenCertificate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "encodedPemCertificate": + err = unpopulate(val, "EncodedPemCertificate", &t.EncodedPemCertificate) + delete(rawMsg, key) + case "expiry": + err = unpopulateDateTimeRFC3339(val, "Expiry", &t.Expiry) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "thumbprint": + err = unpopulate(val, "Thumbprint", &t.Thumbprint) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenCredentialsProperties. +func (t TokenCredentialsProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificates", t.Certificates) + populate(objectMap, "passwords", t.Passwords) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenCredentialsProperties. +func (t *TokenCredentialsProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificates": + err = unpopulate(val, "Certificates", &t.Certificates) + delete(rawMsg, key) + case "passwords": + err = unpopulate(val, "Passwords", &t.Passwords) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenListResult. +func (t TokenListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenListResult. +func (t *TokenListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenPassword. +func (t TokenPassword) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "creationTime", t.CreationTime) + populateDateTimeRFC3339(objectMap, "expiry", t.Expiry) + populate(objectMap, "name", t.Name) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenPassword. +func (t *TokenPassword) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &t.CreationTime) + delete(rawMsg, key) + case "expiry": + err = unpopulateDateTimeRFC3339(val, "Expiry", &t.Expiry) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenProperties. +func (t TokenProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "creationDate", t.CreationDate) + populate(objectMap, "credentials", t.Credentials) + populate(objectMap, "provisioningState", t.ProvisioningState) + populate(objectMap, "scopeMapId", t.ScopeMapID) + populate(objectMap, "status", t.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenProperties. +func (t *TokenProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationDate": + err = unpopulateDateTimeRFC3339(val, "CreationDate", &t.CreationDate) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &t.Credentials) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &t.ProvisioningState) + delete(rawMsg, key) + case "scopeMapId": + err = unpopulate(val, "ScopeMapID", &t.ScopeMapID) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenUpdateParameters. +func (t TokenUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", t.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenUpdateParameters. +func (t *TokenUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TokenUpdateProperties. +func (t TokenUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "credentials", t.Credentials) + populate(objectMap, "scopeMapId", t.ScopeMapID) + populate(objectMap, "status", t.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TokenUpdateProperties. +func (t *TokenUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "credentials": + err = unpopulate(val, "Credentials", &t.Credentials) + delete(rawMsg, key) + case "scopeMapId": + err = unpopulate(val, "ScopeMapID", &t.ScopeMapID) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TriggerProperties. +func (t TriggerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageTrigger", t.BaseImageTrigger) + populate(objectMap, "sourceTriggers", t.SourceTriggers) + populate(objectMap, "timerTriggers", t.TimerTriggers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TriggerProperties. +func (t *TriggerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageTrigger": + err = unpopulate(val, "BaseImageTrigger", &t.BaseImageTrigger) + delete(rawMsg, key) + case "sourceTriggers": + err = unpopulate(val, "SourceTriggers", &t.SourceTriggers) + delete(rawMsg, key) + case "timerTriggers": + err = unpopulate(val, "TimerTriggers", &t.TimerTriggers) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TriggerUpdateParameters. +func (t TriggerUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseImageTrigger", t.BaseImageTrigger) + populate(objectMap, "sourceTriggers", t.SourceTriggers) + populate(objectMap, "timerTriggers", t.TimerTriggers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TriggerUpdateParameters. +func (t *TriggerUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseImageTrigger": + err = unpopulate(val, "BaseImageTrigger", &t.BaseImageTrigger) + delete(rawMsg, key) + case "sourceTriggers": + err = unpopulate(val, "SourceTriggers", &t.SourceTriggers) + delete(rawMsg, key) + case "timerTriggers": + err = unpopulate(val, "TimerTriggers", &t.TimerTriggers) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TrustPolicy. +func (t TrustPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", t.Status) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrustPolicy. +func (t *TrustPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserIdentityProperties. +func (u UserIdentityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserIdentityProperties. +func (u *UserIdentityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Webhook. +func (w Webhook) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "location", w.Location) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "systemData", w.SystemData) + populate(objectMap, "tags", w.Tags) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Webhook. +func (w *Webhook) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &w.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &w.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &w.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WebhookCreateParameters. +func (w WebhookCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", w.Location) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "tags", w.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebhookCreateParameters. +func (w *WebhookCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "location": + err = unpopulate(val, "Location", &w.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WebhookListResult. +func (w WebhookListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebhookListResult. +func (w *WebhookListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &w.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &w.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WebhookProperties. +func (w WebhookProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", w.Actions) + populate(objectMap, "provisioningState", w.ProvisioningState) + populate(objectMap, "scope", w.Scope) + populate(objectMap, "status", w.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebhookProperties. +func (w *WebhookProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &w.Actions) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &w.Scope) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &w.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WebhookPropertiesCreateParameters. +func (w WebhookPropertiesCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", w.Actions) + populate(objectMap, "customHeaders", w.CustomHeaders) + populate(objectMap, "scope", w.Scope) + populate(objectMap, "serviceUri", w.ServiceURI) + populate(objectMap, "status", w.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebhookPropertiesCreateParameters. +func (w *WebhookPropertiesCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &w.Actions) + delete(rawMsg, key) + case "customHeaders": + err = unpopulate(val, "CustomHeaders", &w.CustomHeaders) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &w.Scope) + delete(rawMsg, key) + case "serviceUri": + err = unpopulate(val, "ServiceURI", &w.ServiceURI) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &w.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WebhookPropertiesUpdateParameters. +func (w WebhookPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", w.Actions) + populate(objectMap, "customHeaders", w.CustomHeaders) + populate(objectMap, "scope", w.Scope) + populate(objectMap, "serviceUri", w.ServiceURI) + populate(objectMap, "status", w.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebhookPropertiesUpdateParameters. +func (w *WebhookPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &w.Actions) + delete(rawMsg, key) + case "customHeaders": + err = unpopulate(val, "CustomHeaders", &w.CustomHeaders) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &w.Scope) + delete(rawMsg, key) + case "serviceUri": + err = unpopulate(val, "ServiceURI", &w.ServiceURI) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &w.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WebhookUpdateParameters. +func (w WebhookUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "tags", w.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WebhookUpdateParameters. +func (w *WebhookUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/operations_client.go new file mode 100644 index 0000000000..fb9d983477 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/operations_client.go @@ -0,0 +1,88 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - Lists all of the available Azure Container Registry REST API operations. +// +// Generated from API version 2023-07-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.ContainerRegistry/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/options.go new file mode 100644 index 0000000000..8571ed3a42 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/options.go @@ -0,0 +1,447 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +// AgentPoolsClientBeginCreateOptions contains the optional parameters for the AgentPoolsClient.BeginCreate method. +type AgentPoolsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AgentPoolsClientBeginDeleteOptions contains the optional parameters for the AgentPoolsClient.BeginDelete method. +type AgentPoolsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AgentPoolsClientBeginUpdateOptions contains the optional parameters for the AgentPoolsClient.BeginUpdate method. +type AgentPoolsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AgentPoolsClientGetOptions contains the optional parameters for the AgentPoolsClient.Get method. +type AgentPoolsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AgentPoolsClientGetQueueStatusOptions contains the optional parameters for the AgentPoolsClient.GetQueueStatus method. +type AgentPoolsClientGetQueueStatusOptions struct { + // placeholder for future optional parameters +} + +// AgentPoolsClientListOptions contains the optional parameters for the AgentPoolsClient.NewListPager method. +type AgentPoolsClientListOptions struct { + // placeholder for future optional parameters +} + +// CacheRulesClientBeginCreateOptions contains the optional parameters for the CacheRulesClient.BeginCreate method. +type CacheRulesClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CacheRulesClientBeginDeleteOptions contains the optional parameters for the CacheRulesClient.BeginDelete method. +type CacheRulesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CacheRulesClientBeginUpdateOptions contains the optional parameters for the CacheRulesClient.BeginUpdate method. +type CacheRulesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CacheRulesClientGetOptions contains the optional parameters for the CacheRulesClient.Get method. +type CacheRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CacheRulesClientListOptions contains the optional parameters for the CacheRulesClient.NewListPager method. +type CacheRulesClientListOptions struct { + // placeholder for future optional parameters +} + +// CredentialSetsClientBeginCreateOptions contains the optional parameters for the CredentialSetsClient.BeginCreate method. +type CredentialSetsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CredentialSetsClientBeginDeleteOptions contains the optional parameters for the CredentialSetsClient.BeginDelete method. +type CredentialSetsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CredentialSetsClientBeginUpdateOptions contains the optional parameters for the CredentialSetsClient.BeginUpdate method. +type CredentialSetsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// CredentialSetsClientGetOptions contains the optional parameters for the CredentialSetsClient.Get method. +type CredentialSetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// CredentialSetsClientListOptions contains the optional parameters for the CredentialSetsClient.NewListPager method. +type CredentialSetsClientListOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginCreateOrUpdate +// method. +type PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +type PrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +type PrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListPager +// method. +type PrivateEndpointConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientBeginCreateOptions contains the optional parameters for the RegistriesClient.BeginCreate method. +type RegistriesClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RegistriesClientBeginDeleteOptions contains the optional parameters for the RegistriesClient.BeginDelete method. +type RegistriesClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RegistriesClientBeginGenerateCredentialsOptions contains the optional parameters for the RegistriesClient.BeginGenerateCredentials +// method. +type RegistriesClientBeginGenerateCredentialsOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RegistriesClientBeginImportImageOptions contains the optional parameters for the RegistriesClient.BeginImportImage method. +type RegistriesClientBeginImportImageOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RegistriesClientBeginScheduleRunOptions contains the optional parameters for the RegistriesClient.BeginScheduleRun method. +type RegistriesClientBeginScheduleRunOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RegistriesClientBeginUpdateOptions contains the optional parameters for the RegistriesClient.BeginUpdate method. +type RegistriesClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RegistriesClientCheckNameAvailabilityOptions contains the optional parameters for the RegistriesClient.CheckNameAvailability +// method. +type RegistriesClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientGetBuildSourceUploadURLOptions contains the optional parameters for the RegistriesClient.GetBuildSourceUploadURL +// method. +type RegistriesClientGetBuildSourceUploadURLOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientGetOptions contains the optional parameters for the RegistriesClient.Get method. +type RegistriesClientGetOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientGetPrivateLinkResourceOptions contains the optional parameters for the RegistriesClient.GetPrivateLinkResource +// method. +type RegistriesClientGetPrivateLinkResourceOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientListByResourceGroupOptions contains the optional parameters for the RegistriesClient.NewListByResourceGroupPager +// method. +type RegistriesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientListCredentialsOptions contains the optional parameters for the RegistriesClient.ListCredentials method. +type RegistriesClientListCredentialsOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientListOptions contains the optional parameters for the RegistriesClient.NewListPager method. +type RegistriesClientListOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientListPrivateLinkResourcesOptions contains the optional parameters for the RegistriesClient.NewListPrivateLinkResourcesPager +// method. +type RegistriesClientListPrivateLinkResourcesOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientListUsagesOptions contains the optional parameters for the RegistriesClient.ListUsages method. +type RegistriesClientListUsagesOptions struct { + // placeholder for future optional parameters +} + +// RegistriesClientRegenerateCredentialOptions contains the optional parameters for the RegistriesClient.RegenerateCredential +// method. +type RegistriesClientRegenerateCredentialOptions struct { + // placeholder for future optional parameters +} + +// ReplicationsClientBeginCreateOptions contains the optional parameters for the ReplicationsClient.BeginCreate method. +type ReplicationsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ReplicationsClientBeginDeleteOptions contains the optional parameters for the ReplicationsClient.BeginDelete method. +type ReplicationsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ReplicationsClientBeginUpdateOptions contains the optional parameters for the ReplicationsClient.BeginUpdate method. +type ReplicationsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ReplicationsClientGetOptions contains the optional parameters for the ReplicationsClient.Get method. +type ReplicationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ReplicationsClientListOptions contains the optional parameters for the ReplicationsClient.NewListPager method. +type ReplicationsClientListOptions struct { + // placeholder for future optional parameters +} + +// RunsClientBeginCancelOptions contains the optional parameters for the RunsClient.BeginCancel method. +type RunsClientBeginCancelOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RunsClientBeginUpdateOptions contains the optional parameters for the RunsClient.BeginUpdate method. +type RunsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// RunsClientGetLogSasURLOptions contains the optional parameters for the RunsClient.GetLogSasURL method. +type RunsClientGetLogSasURLOptions struct { + // placeholder for future optional parameters +} + +// RunsClientGetOptions contains the optional parameters for the RunsClient.Get method. +type RunsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RunsClientListOptions contains the optional parameters for the RunsClient.NewListPager method. +type RunsClientListOptions struct { + // The runs filter to apply on the operation. Arithmetic operators are not supported. The allowed string function is 'contains'. + // All logical operators except 'Not', 'Has', 'All' are allowed. + Filter *string + + // $top is supported for get list of runs, which limits the maximum number of runs to return. + Top *int32 +} + +// ScopeMapsClientBeginCreateOptions contains the optional parameters for the ScopeMapsClient.BeginCreate method. +type ScopeMapsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ScopeMapsClientBeginDeleteOptions contains the optional parameters for the ScopeMapsClient.BeginDelete method. +type ScopeMapsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ScopeMapsClientBeginUpdateOptions contains the optional parameters for the ScopeMapsClient.BeginUpdate method. +type ScopeMapsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ScopeMapsClientGetOptions contains the optional parameters for the ScopeMapsClient.Get method. +type ScopeMapsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScopeMapsClientListOptions contains the optional parameters for the ScopeMapsClient.NewListPager method. +type ScopeMapsClientListOptions struct { + // placeholder for future optional parameters +} + +// TaskRunsClientBeginCreateOptions contains the optional parameters for the TaskRunsClient.BeginCreate method. +type TaskRunsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TaskRunsClientBeginDeleteOptions contains the optional parameters for the TaskRunsClient.BeginDelete method. +type TaskRunsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TaskRunsClientBeginUpdateOptions contains the optional parameters for the TaskRunsClient.BeginUpdate method. +type TaskRunsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TaskRunsClientGetDetailsOptions contains the optional parameters for the TaskRunsClient.GetDetails method. +type TaskRunsClientGetDetailsOptions struct { + // placeholder for future optional parameters +} + +// TaskRunsClientGetOptions contains the optional parameters for the TaskRunsClient.Get method. +type TaskRunsClientGetOptions struct { + // placeholder for future optional parameters +} + +// TaskRunsClientListOptions contains the optional parameters for the TaskRunsClient.NewListPager method. +type TaskRunsClientListOptions struct { + // placeholder for future optional parameters +} + +// TasksClientBeginCreateOptions contains the optional parameters for the TasksClient.BeginCreate method. +type TasksClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TasksClientBeginDeleteOptions contains the optional parameters for the TasksClient.BeginDelete method. +type TasksClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TasksClientBeginUpdateOptions contains the optional parameters for the TasksClient.BeginUpdate method. +type TasksClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TasksClientGetDetailsOptions contains the optional parameters for the TasksClient.GetDetails method. +type TasksClientGetDetailsOptions struct { + // placeholder for future optional parameters +} + +// TasksClientGetOptions contains the optional parameters for the TasksClient.Get method. +type TasksClientGetOptions struct { + // placeholder for future optional parameters +} + +// TasksClientListOptions contains the optional parameters for the TasksClient.NewListPager method. +type TasksClientListOptions struct { + // placeholder for future optional parameters +} + +// TokensClientBeginCreateOptions contains the optional parameters for the TokensClient.BeginCreate method. +type TokensClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TokensClientBeginDeleteOptions contains the optional parameters for the TokensClient.BeginDelete method. +type TokensClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TokensClientBeginUpdateOptions contains the optional parameters for the TokensClient.BeginUpdate method. +type TokensClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// TokensClientGetOptions contains the optional parameters for the TokensClient.Get method. +type TokensClientGetOptions struct { + // placeholder for future optional parameters +} + +// TokensClientListOptions contains the optional parameters for the TokensClient.NewListPager method. +type TokensClientListOptions struct { + // placeholder for future optional parameters +} + +// WebhooksClientBeginCreateOptions contains the optional parameters for the WebhooksClient.BeginCreate method. +type WebhooksClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WebhooksClientBeginDeleteOptions contains the optional parameters for the WebhooksClient.BeginDelete method. +type WebhooksClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WebhooksClientBeginUpdateOptions contains the optional parameters for the WebhooksClient.BeginUpdate method. +type WebhooksClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WebhooksClientGetCallbackConfigOptions contains the optional parameters for the WebhooksClient.GetCallbackConfig method. +type WebhooksClientGetCallbackConfigOptions struct { + // placeholder for future optional parameters +} + +// WebhooksClientGetOptions contains the optional parameters for the WebhooksClient.Get method. +type WebhooksClientGetOptions struct { + // placeholder for future optional parameters +} + +// WebhooksClientListEventsOptions contains the optional parameters for the WebhooksClient.NewListEventsPager method. +type WebhooksClientListEventsOptions struct { + // placeholder for future optional parameters +} + +// WebhooksClientListOptions contains the optional parameters for the WebhooksClient.NewListPager method. +type WebhooksClientListOptions struct { + // placeholder for future optional parameters +} + +// WebhooksClientPingOptions contains the optional parameters for the WebhooksClient.Ping method. +type WebhooksClientPingOptions struct { + // placeholder for future optional parameters +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/polymorphic_helpers.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/polymorphic_helpers.go new file mode 100644 index 0000000000..bdd88e76de --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/polymorphic_helpers.go @@ -0,0 +1,88 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import "encoding/json" + +func unmarshalRunRequestClassification(rawMsg json.RawMessage) (RunRequestClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b RunRequestClassification + switch m["type"] { + case "DockerBuildRequest": + b = &DockerBuildRequest{} + case "EncodedTaskRunRequest": + b = &EncodedTaskRunRequest{} + case "FileTaskRunRequest": + b = &FileTaskRunRequest{} + case "TaskRunRequest": + b = &TaskRunRequest{} + default: + b = &RunRequest{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalTaskStepPropertiesClassification(rawMsg json.RawMessage) (TaskStepPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b TaskStepPropertiesClassification + switch m["type"] { + case string(StepTypeDocker): + b = &DockerBuildStep{} + case string(StepTypeEncodedTask): + b = &EncodedTaskStep{} + case string(StepTypeFileTask): + b = &FileTaskStep{} + default: + b = &TaskStepProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalTaskStepUpdateParametersClassification(rawMsg json.RawMessage) (TaskStepUpdateParametersClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b TaskStepUpdateParametersClassification + switch m["type"] { + case string(StepTypeDocker): + b = &DockerBuildStepUpdateParameters{} + case string(StepTypeEncodedTask): + b = &EncodedTaskStepUpdateParameters{} + case string(StepTypeFileTask): + b = &FileTaskStepUpdateParameters{} + default: + b = &TaskStepUpdateParameters{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/privateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/privateendpointconnections_client.go new file mode 100644 index 0000000000..695290cc97 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/privateendpointconnections_client.go @@ -0,0 +1,346 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Update the state of specified private endpoint connection associated with the container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - privateEndpointConnectionName - The name of the private endpoint connection. +// - privateEndpointConnection - The parameters for creating a private endpoint connection. +// - options - PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginCreateOrUpdate +// method. +func (client *PrivateEndpointConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[PrivateEndpointConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, registryName, privateEndpointConnectionName, privateEndpointConnection, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointConnectionsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Update the state of specified private endpoint connection associated with the container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *PrivateEndpointConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, registryName, privateEndpointConnectionName, privateEndpointConnection, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PrivateEndpointConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, privateEndpointConnection); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified private endpoint connection associated with the container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - privateEndpointConnectionName - The name of the private endpoint connection. +// - options - PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[PrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointConnectionsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified private endpoint connection associated with the container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Get the specified private endpoint connection associated with the container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - privateEndpointConnectionName - The name of the private endpoint connection. +// - options - PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (PrivateEndpointConnectionsClientGetResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientGetResponse, error) { + result := PrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all private endpoint connections in a container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListPager +// method. +func (client *PrivateEndpointConnectionsClient) NewListPager(resourceGroupName string, registryName string, options *PrivateEndpointConnectionsClientListOptions) *runtime.Pager[PrivateEndpointConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointConnectionsClientListResponse]{ + More: func(page PrivateEndpointConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointConnectionsClientListResponse) (PrivateEndpointConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateEndpointConnectionsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *PrivateEndpointConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientListResponse, error) { + result := PrivateEndpointConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/registries_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/registries_client.go new file mode 100644 index 0000000000..d33c46433f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/registries_client.go @@ -0,0 +1,1156 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RegistriesClient contains the methods for the Registries group. +// Don't use this type directly, use NewRegistriesClient() instead. +type RegistriesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRegistriesClient creates a new instance of RegistriesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewRegistriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RegistriesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RegistriesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckNameAvailability - Checks whether the container registry name is available for use. The name must contain only alphanumeric +// characters, be globally unique, and between 5 and 50 characters in length. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - registryNameCheckRequest - The object containing information for the availability request. +// - options - RegistriesClientCheckNameAvailabilityOptions contains the optional parameters for the RegistriesClient.CheckNameAvailability +// method. +func (client *RegistriesClient) CheckNameAvailability(ctx context.Context, registryNameCheckRequest RegistryNameCheckRequest, options *RegistriesClientCheckNameAvailabilityOptions) (RegistriesClientCheckNameAvailabilityResponse, error) { + var err error + const operationName = "RegistriesClient.CheckNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkNameAvailabilityCreateRequest(ctx, registryNameCheckRequest, options) + if err != nil { + return RegistriesClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *RegistriesClient) checkNameAvailabilityCreateRequest(ctx context.Context, registryNameCheckRequest RegistryNameCheckRequest, options *RegistriesClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerRegistry/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, registryNameCheckRequest); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *RegistriesClient) checkNameAvailabilityHandleResponse(resp *http.Response) (RegistriesClientCheckNameAvailabilityResponse, error) { + result := RegistriesClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RegistryNameStatus); err != nil { + return RegistriesClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreate - Creates a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - registry - The parameters for creating a container registry. +// - options - RegistriesClientBeginCreateOptions contains the optional parameters for the RegistriesClient.BeginCreate method. +func (client *RegistriesClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, registry Registry, options *RegistriesClientBeginCreateOptions) (*runtime.Poller[RegistriesClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, registry, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RegistriesClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RegistriesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *RegistriesClient) create(ctx context.Context, resourceGroupName string, registryName string, registry Registry, options *RegistriesClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "RegistriesClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, registry, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *RegistriesClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, registry Registry, options *RegistriesClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, registry); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - RegistriesClientBeginDeleteOptions contains the optional parameters for the RegistriesClient.BeginDelete method. +func (client *RegistriesClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientBeginDeleteOptions) (*runtime.Poller[RegistriesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RegistriesClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RegistriesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *RegistriesClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RegistriesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RegistriesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// BeginGenerateCredentials - Generate keys for a token of a specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - generateCredentialsParameters - The parameters for generating credentials. +// - options - RegistriesClientBeginGenerateCredentialsOptions contains the optional parameters for the RegistriesClient.BeginGenerateCredentials +// method. +func (client *RegistriesClient) BeginGenerateCredentials(ctx context.Context, resourceGroupName string, registryName string, generateCredentialsParameters GenerateCredentialsParameters, options *RegistriesClientBeginGenerateCredentialsOptions) (*runtime.Poller[RegistriesClientGenerateCredentialsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.generateCredentials(ctx, resourceGroupName, registryName, generateCredentialsParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RegistriesClientGenerateCredentialsResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RegistriesClientGenerateCredentialsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// GenerateCredentials - Generate keys for a token of a specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *RegistriesClient) generateCredentials(ctx context.Context, resourceGroupName string, registryName string, generateCredentialsParameters GenerateCredentialsParameters, options *RegistriesClientBeginGenerateCredentialsOptions) (*http.Response, error) { + var err error + const operationName = "RegistriesClient.BeginGenerateCredentials" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generateCredentialsCreateRequest(ctx, resourceGroupName, registryName, generateCredentialsParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// generateCredentialsCreateRequest creates the GenerateCredentials request. +func (client *RegistriesClient) generateCredentialsCreateRequest(ctx context.Context, resourceGroupName string, registryName string, generateCredentialsParameters GenerateCredentialsParameters, options *RegistriesClientBeginGenerateCredentialsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/generateCredentials" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, generateCredentialsParameters); err != nil { + return nil, err + } + return req, nil +} + +// Get - Gets the properties of the specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - RegistriesClientGetOptions contains the optional parameters for the RegistriesClient.Get method. +func (client *RegistriesClient) Get(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientGetOptions) (RegistriesClientGetResponse, error) { + var err error + const operationName = "RegistriesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, options) + if err != nil { + return RegistriesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RegistriesClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RegistriesClient) getHandleResponse(resp *http.Response) (RegistriesClientGetResponse, error) { + result := RegistriesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Registry); err != nil { + return RegistriesClientGetResponse{}, err + } + return result, nil +} + +// GetBuildSourceUploadURL - Get the upload location for the user to be able to upload the source. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - options - RegistriesClientGetBuildSourceUploadURLOptions contains the optional parameters for the RegistriesClient.GetBuildSourceUploadURL +// method. +func (client *RegistriesClient) GetBuildSourceUploadURL(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientGetBuildSourceUploadURLOptions) (RegistriesClientGetBuildSourceUploadURLResponse, error) { + var err error + const operationName = "RegistriesClient.GetBuildSourceUploadURL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getBuildSourceUploadURLCreateRequest(ctx, resourceGroupName, registryName, options) + if err != nil { + return RegistriesClientGetBuildSourceUploadURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientGetBuildSourceUploadURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientGetBuildSourceUploadURLResponse{}, err + } + resp, err := client.getBuildSourceUploadURLHandleResponse(httpResp) + return resp, err +} + +// getBuildSourceUploadURLCreateRequest creates the GetBuildSourceUploadURL request. +func (client *RegistriesClient) getBuildSourceUploadURLCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientGetBuildSourceUploadURLOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listBuildSourceUploadUrl" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getBuildSourceUploadURLHandleResponse handles the GetBuildSourceUploadURL response. +func (client *RegistriesClient) getBuildSourceUploadURLHandleResponse(resp *http.Response) (RegistriesClientGetBuildSourceUploadURLResponse, error) { + result := RegistriesClientGetBuildSourceUploadURLResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SourceUploadDefinition); err != nil { + return RegistriesClientGetBuildSourceUploadURLResponse{}, err + } + return result, nil +} + +// GetPrivateLinkResource - Gets a private link resource by a specified group name for a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - groupName - The name of the private link resource. +// - options - RegistriesClientGetPrivateLinkResourceOptions contains the optional parameters for the RegistriesClient.GetPrivateLinkResource +// method. +func (client *RegistriesClient) GetPrivateLinkResource(ctx context.Context, resourceGroupName string, registryName string, groupName string, options *RegistriesClientGetPrivateLinkResourceOptions) (RegistriesClientGetPrivateLinkResourceResponse, error) { + var err error + const operationName = "RegistriesClient.GetPrivateLinkResource" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPrivateLinkResourceCreateRequest(ctx, resourceGroupName, registryName, groupName, options) + if err != nil { + return RegistriesClientGetPrivateLinkResourceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientGetPrivateLinkResourceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientGetPrivateLinkResourceResponse{}, err + } + resp, err := client.getPrivateLinkResourceHandleResponse(httpResp) + return resp, err +} + +// getPrivateLinkResourceCreateRequest creates the GetPrivateLinkResource request. +func (client *RegistriesClient) getPrivateLinkResourceCreateRequest(ctx context.Context, resourceGroupName string, registryName string, groupName string, options *RegistriesClientGetPrivateLinkResourceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/privateLinkResources/{groupName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if groupName == "" { + return nil, errors.New("parameter groupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getPrivateLinkResourceHandleResponse handles the GetPrivateLinkResource response. +func (client *RegistriesClient) getPrivateLinkResourceHandleResponse(resp *http.Response) (RegistriesClientGetPrivateLinkResourceResponse, error) { + result := RegistriesClientGetPrivateLinkResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResource); err != nil { + return RegistriesClientGetPrivateLinkResourceResponse{}, err + } + return result, nil +} + +// BeginImportImage - Copies an image to this container registry from the specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - parameters - The parameters specifying the image to copy and the source container registry. +// - options - RegistriesClientBeginImportImageOptions contains the optional parameters for the RegistriesClient.BeginImportImage +// method. +func (client *RegistriesClient) BeginImportImage(ctx context.Context, resourceGroupName string, registryName string, parameters ImportImageParameters, options *RegistriesClientBeginImportImageOptions) (*runtime.Poller[RegistriesClientImportImageResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.importImage(ctx, resourceGroupName, registryName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RegistriesClientImportImageResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RegistriesClientImportImageResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ImportImage - Copies an image to this container registry from the specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *RegistriesClient) importImage(ctx context.Context, resourceGroupName string, registryName string, parameters ImportImageParameters, options *RegistriesClientBeginImportImageOptions) (*http.Response, error) { + var err error + const operationName = "RegistriesClient.BeginImportImage" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.importImageCreateRequest(ctx, resourceGroupName, registryName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// importImageCreateRequest creates the ImportImage request. +func (client *RegistriesClient) importImageCreateRequest(ctx context.Context, resourceGroupName string, registryName string, parameters ImportImageParameters, options *RegistriesClientBeginImportImageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/importImage" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// NewListPager - Lists all the container registries under the specified subscription. +// +// Generated from API version 2023-07-01 +// - options - RegistriesClientListOptions contains the optional parameters for the RegistriesClient.NewListPager method. +func (client *RegistriesClient) NewListPager(options *RegistriesClientListOptions) *runtime.Pager[RegistriesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RegistriesClientListResponse]{ + More: func(page RegistriesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RegistriesClientListResponse) (RegistriesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RegistriesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return RegistriesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RegistriesClient) listCreateRequest(ctx context.Context, options *RegistriesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerRegistry/registries" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RegistriesClient) listHandleResponse(resp *http.Response) (RegistriesClientListResponse, error) { + result := RegistriesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RegistryListResult); err != nil { + return RegistriesClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the container registries under the specified resource group. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - RegistriesClientListByResourceGroupOptions contains the optional parameters for the RegistriesClient.NewListByResourceGroupPager +// method. +func (client *RegistriesClient) NewListByResourceGroupPager(resourceGroupName string, options *RegistriesClientListByResourceGroupOptions) *runtime.Pager[RegistriesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[RegistriesClientListByResourceGroupResponse]{ + More: func(page RegistriesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RegistriesClientListByResourceGroupResponse) (RegistriesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RegistriesClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return RegistriesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *RegistriesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *RegistriesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *RegistriesClient) listByResourceGroupHandleResponse(resp *http.Response) (RegistriesClientListByResourceGroupResponse, error) { + result := RegistriesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RegistryListResult); err != nil { + return RegistriesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// ListCredentials - Lists the login credentials for the specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - RegistriesClientListCredentialsOptions contains the optional parameters for the RegistriesClient.ListCredentials +// method. +func (client *RegistriesClient) ListCredentials(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientListCredentialsOptions) (RegistriesClientListCredentialsResponse, error) { + var err error + const operationName = "RegistriesClient.ListCredentials" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCredentialsCreateRequest(ctx, resourceGroupName, registryName, options) + if err != nil { + return RegistriesClientListCredentialsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientListCredentialsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientListCredentialsResponse{}, err + } + resp, err := client.listCredentialsHandleResponse(httpResp) + return resp, err +} + +// listCredentialsCreateRequest creates the ListCredentials request. +func (client *RegistriesClient) listCredentialsCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientListCredentialsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listCredentials" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listCredentialsHandleResponse handles the ListCredentials response. +func (client *RegistriesClient) listCredentialsHandleResponse(resp *http.Response) (RegistriesClientListCredentialsResponse, error) { + result := RegistriesClientListCredentialsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RegistryListCredentialsResult); err != nil { + return RegistriesClientListCredentialsResponse{}, err + } + return result, nil +} + +// NewListPrivateLinkResourcesPager - Lists the private link resources for a container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - RegistriesClientListPrivateLinkResourcesOptions contains the optional parameters for the RegistriesClient.NewListPrivateLinkResourcesPager +// method. +func (client *RegistriesClient) NewListPrivateLinkResourcesPager(resourceGroupName string, registryName string, options *RegistriesClientListPrivateLinkResourcesOptions) *runtime.Pager[RegistriesClientListPrivateLinkResourcesResponse] { + return runtime.NewPager(runtime.PagingHandler[RegistriesClientListPrivateLinkResourcesResponse]{ + More: func(page RegistriesClientListPrivateLinkResourcesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RegistriesClientListPrivateLinkResourcesResponse) (RegistriesClientListPrivateLinkResourcesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RegistriesClient.NewListPrivateLinkResourcesPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listPrivateLinkResourcesCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return RegistriesClientListPrivateLinkResourcesResponse{}, err + } + return client.listPrivateLinkResourcesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPrivateLinkResourcesCreateRequest creates the ListPrivateLinkResources request. +func (client *RegistriesClient) listPrivateLinkResourcesCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientListPrivateLinkResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPrivateLinkResourcesHandleResponse handles the ListPrivateLinkResources response. +func (client *RegistriesClient) listPrivateLinkResourcesHandleResponse(resp *http.Response) (RegistriesClientListPrivateLinkResourcesResponse, error) { + result := RegistriesClientListPrivateLinkResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return RegistriesClientListPrivateLinkResourcesResponse{}, err + } + return result, nil +} + +// ListUsages - Gets the quota usages for the specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - RegistriesClientListUsagesOptions contains the optional parameters for the RegistriesClient.ListUsages method. +func (client *RegistriesClient) ListUsages(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientListUsagesOptions) (RegistriesClientListUsagesResponse, error) { + var err error + const operationName = "RegistriesClient.ListUsages" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listUsagesCreateRequest(ctx, resourceGroupName, registryName, options) + if err != nil { + return RegistriesClientListUsagesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientListUsagesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientListUsagesResponse{}, err + } + resp, err := client.listUsagesHandleResponse(httpResp) + return resp, err +} + +// listUsagesCreateRequest creates the ListUsages request. +func (client *RegistriesClient) listUsagesCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RegistriesClientListUsagesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listUsages" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listUsagesHandleResponse handles the ListUsages response. +func (client *RegistriesClient) listUsagesHandleResponse(resp *http.Response) (RegistriesClientListUsagesResponse, error) { + result := RegistriesClientListUsagesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RegistryUsageListResult); err != nil { + return RegistriesClientListUsagesResponse{}, err + } + return result, nil +} + +// RegenerateCredential - Regenerates one of the login credentials for the specified container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - regenerateCredentialParameters - Specifies name of the password which should be regenerated -- password or password2. +// - options - RegistriesClientRegenerateCredentialOptions contains the optional parameters for the RegistriesClient.RegenerateCredential +// method. +func (client *RegistriesClient) RegenerateCredential(ctx context.Context, resourceGroupName string, registryName string, regenerateCredentialParameters RegenerateCredentialParameters, options *RegistriesClientRegenerateCredentialOptions) (RegistriesClientRegenerateCredentialResponse, error) { + var err error + const operationName = "RegistriesClient.RegenerateCredential" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.regenerateCredentialCreateRequest(ctx, resourceGroupName, registryName, regenerateCredentialParameters, options) + if err != nil { + return RegistriesClientRegenerateCredentialResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RegistriesClientRegenerateCredentialResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RegistriesClientRegenerateCredentialResponse{}, err + } + resp, err := client.regenerateCredentialHandleResponse(httpResp) + return resp, err +} + +// regenerateCredentialCreateRequest creates the RegenerateCredential request. +func (client *RegistriesClient) regenerateCredentialCreateRequest(ctx context.Context, resourceGroupName string, registryName string, regenerateCredentialParameters RegenerateCredentialParameters, options *RegistriesClientRegenerateCredentialOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/regenerateCredential" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, regenerateCredentialParameters); err != nil { + return nil, err + } + return req, nil +} + +// regenerateCredentialHandleResponse handles the RegenerateCredential response. +func (client *RegistriesClient) regenerateCredentialHandleResponse(resp *http.Response) (RegistriesClientRegenerateCredentialResponse, error) { + result := RegistriesClientRegenerateCredentialResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RegistryListCredentialsResult); err != nil { + return RegistriesClientRegenerateCredentialResponse{}, err + } + return result, nil +} + +// BeginScheduleRun - Schedules a new run based on the request parameters and add it to the run queue. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - runRequest - The parameters of a run that needs to scheduled. +// - options - RegistriesClientBeginScheduleRunOptions contains the optional parameters for the RegistriesClient.BeginScheduleRun +// method. +func (client *RegistriesClient) BeginScheduleRun(ctx context.Context, resourceGroupName string, registryName string, runRequest RunRequestClassification, options *RegistriesClientBeginScheduleRunOptions) (*runtime.Poller[RegistriesClientScheduleRunResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.scheduleRun(ctx, resourceGroupName, registryName, runRequest, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RegistriesClientScheduleRunResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RegistriesClientScheduleRunResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ScheduleRun - Schedules a new run based on the request parameters and add it to the run queue. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *RegistriesClient) scheduleRun(ctx context.Context, resourceGroupName string, registryName string, runRequest RunRequestClassification, options *RegistriesClientBeginScheduleRunOptions) (*http.Response, error) { + var err error + const operationName = "RegistriesClient.BeginScheduleRun" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.scheduleRunCreateRequest(ctx, resourceGroupName, registryName, runRequest, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// scheduleRunCreateRequest creates the ScheduleRun request. +func (client *RegistriesClient) scheduleRunCreateRequest(ctx context.Context, resourceGroupName string, registryName string, runRequest RunRequestClassification, options *RegistriesClientBeginScheduleRunOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scheduleRun" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, runRequest); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdate - Updates a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - registryUpdateParameters - The parameters for updating a container registry. +// - options - RegistriesClientBeginUpdateOptions contains the optional parameters for the RegistriesClient.BeginUpdate method. +func (client *RegistriesClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, registryUpdateParameters RegistryUpdateParameters, options *RegistriesClientBeginUpdateOptions) (*runtime.Poller[RegistriesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, registryUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RegistriesClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RegistriesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *RegistriesClient) update(ctx context.Context, resourceGroupName string, registryName string, registryUpdateParameters RegistryUpdateParameters, options *RegistriesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RegistriesClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, registryUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *RegistriesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, registryUpdateParameters RegistryUpdateParameters, options *RegistriesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, registryUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/replications_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/replications_client.go new file mode 100644 index 0000000000..abefe243ba --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/replications_client.go @@ -0,0 +1,430 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ReplicationsClient contains the methods for the Replications group. +// Don't use this type directly, use NewReplicationsClient() instead. +type ReplicationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewReplicationsClient creates a new instance of ReplicationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewReplicationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ReplicationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ReplicationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a replication for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - replicationName - The name of the replication. +// - replication - The parameters for creating a replication. +// - options - ReplicationsClientBeginCreateOptions contains the optional parameters for the ReplicationsClient.BeginCreate +// method. +func (client *ReplicationsClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, replicationName string, replication Replication, options *ReplicationsClientBeginCreateOptions) (*runtime.Poller[ReplicationsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, replicationName, replication, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ReplicationsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ReplicationsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a replication for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ReplicationsClient) create(ctx context.Context, resourceGroupName string, registryName string, replicationName string, replication Replication, options *ReplicationsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "ReplicationsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, replicationName, replication, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *ReplicationsClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, replicationName string, replication Replication, options *ReplicationsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications/{replicationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if replicationName == "" { + return nil, errors.New("parameter replicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{replicationName}", url.PathEscape(replicationName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, replication); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a replication from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - replicationName - The name of the replication. +// - options - ReplicationsClientBeginDeleteOptions contains the optional parameters for the ReplicationsClient.BeginDelete +// method. +func (client *ReplicationsClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsClientBeginDeleteOptions) (*runtime.Poller[ReplicationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, replicationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ReplicationsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ReplicationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a replication from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ReplicationsClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ReplicationsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, replicationName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ReplicationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications/{replicationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if replicationName == "" { + return nil, errors.New("parameter replicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{replicationName}", url.PathEscape(replicationName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Gets the properties of the specified replication. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - replicationName - The name of the replication. +// - options - ReplicationsClientGetOptions contains the optional parameters for the ReplicationsClient.Get method. +func (client *ReplicationsClient) Get(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsClientGetOptions) (ReplicationsClientGetResponse, error) { + var err error + const operationName = "ReplicationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, replicationName, options) + if err != nil { + return ReplicationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReplicationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReplicationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ReplicationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications/{replicationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if replicationName == "" { + return nil, errors.New("parameter replicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{replicationName}", url.PathEscape(replicationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ReplicationsClient) getHandleResponse(resp *http.Response) (ReplicationsClientGetResponse, error) { + result := ReplicationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Replication); err != nil { + return ReplicationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the replications for the specified container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - ReplicationsClientListOptions contains the optional parameters for the ReplicationsClient.NewListPager method. +func (client *ReplicationsClient) NewListPager(resourceGroupName string, registryName string, options *ReplicationsClientListOptions) *runtime.Pager[ReplicationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ReplicationsClientListResponse]{ + More: func(page ReplicationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ReplicationsClientListResponse) (ReplicationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ReplicationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return ReplicationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ReplicationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *ReplicationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ReplicationsClient) listHandleResponse(resp *http.Response) (ReplicationsClientListResponse, error) { + result := ReplicationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ReplicationListResult); err != nil { + return ReplicationsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a replication for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - replicationName - The name of the replication. +// - replicationUpdateParameters - The parameters for updating a replication. +// - options - ReplicationsClientBeginUpdateOptions contains the optional parameters for the ReplicationsClient.BeginUpdate +// method. +func (client *ReplicationsClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, replicationName string, replicationUpdateParameters ReplicationUpdateParameters, options *ReplicationsClientBeginUpdateOptions) (*runtime.Poller[ReplicationsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, replicationName, replicationUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ReplicationsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ReplicationsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a replication for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ReplicationsClient) update(ctx context.Context, resourceGroupName string, registryName string, replicationName string, replicationUpdateParameters ReplicationUpdateParameters, options *ReplicationsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ReplicationsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, replicationName, replicationUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ReplicationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, replicationName string, replicationUpdateParameters ReplicationUpdateParameters, options *ReplicationsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications/{replicationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if replicationName == "" { + return nil, errors.New("parameter replicationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{replicationName}", url.PathEscape(replicationName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, replicationUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/response_types.go new file mode 100644 index 0000000000..08ed393407 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/response_types.go @@ -0,0 +1,469 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +// AgentPoolsClientCreateResponse contains the response from method AgentPoolsClient.BeginCreate. +type AgentPoolsClientCreateResponse struct { + // The agentpool that has the ARM resource and properties. + // The agentpool will have all information to create an agent pool. + AgentPool +} + +// AgentPoolsClientDeleteResponse contains the response from method AgentPoolsClient.BeginDelete. +type AgentPoolsClientDeleteResponse struct { + // placeholder for future response values +} + +// AgentPoolsClientGetQueueStatusResponse contains the response from method AgentPoolsClient.GetQueueStatus. +type AgentPoolsClientGetQueueStatusResponse struct { + // The QueueStatus of Agent Pool + AgentPoolQueueStatus +} + +// AgentPoolsClientGetResponse contains the response from method AgentPoolsClient.Get. +type AgentPoolsClientGetResponse struct { + // The agentpool that has the ARM resource and properties. + // The agentpool will have all information to create an agent pool. + AgentPool +} + +// AgentPoolsClientListResponse contains the response from method AgentPoolsClient.NewListPager. +type AgentPoolsClientListResponse struct { + // The collection of agent pools. + AgentPoolListResult +} + +// AgentPoolsClientUpdateResponse contains the response from method AgentPoolsClient.BeginUpdate. +type AgentPoolsClientUpdateResponse struct { + // The agentpool that has the ARM resource and properties. + // The agentpool will have all information to create an agent pool. + AgentPool +} + +// CacheRulesClientCreateResponse contains the response from method CacheRulesClient.BeginCreate. +type CacheRulesClientCreateResponse struct { + // An object that represents a cache rule for a container registry. + CacheRule +} + +// CacheRulesClientDeleteResponse contains the response from method CacheRulesClient.BeginDelete. +type CacheRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// CacheRulesClientGetResponse contains the response from method CacheRulesClient.Get. +type CacheRulesClientGetResponse struct { + // An object that represents a cache rule for a container registry. + CacheRule +} + +// CacheRulesClientListResponse contains the response from method CacheRulesClient.NewListPager. +type CacheRulesClientListResponse struct { + // The result of a request to list cache rules for a container registry. + CacheRulesListResult +} + +// CacheRulesClientUpdateResponse contains the response from method CacheRulesClient.BeginUpdate. +type CacheRulesClientUpdateResponse struct { + // An object that represents a cache rule for a container registry. + CacheRule +} + +// CredentialSetsClientCreateResponse contains the response from method CredentialSetsClient.BeginCreate. +type CredentialSetsClientCreateResponse struct { + // An object that represents a credential set resource for a container registry. + CredentialSet +} + +// CredentialSetsClientDeleteResponse contains the response from method CredentialSetsClient.BeginDelete. +type CredentialSetsClientDeleteResponse struct { + // placeholder for future response values +} + +// CredentialSetsClientGetResponse contains the response from method CredentialSetsClient.Get. +type CredentialSetsClientGetResponse struct { + // An object that represents a credential set resource for a container registry. + CredentialSet +} + +// CredentialSetsClientListResponse contains the response from method CredentialSetsClient.NewListPager. +type CredentialSetsClientListResponse struct { + // The result of a request to list credential sets for a container registry. + CredentialSetListResult +} + +// CredentialSetsClientUpdateResponse contains the response from method CredentialSetsClient.BeginUpdate. +type CredentialSetsClientUpdateResponse struct { + // An object that represents a credential set resource for a container registry. + CredentialSet +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // The result of a request to list container registry operations. + OperationListResult +} + +// PrivateEndpointConnectionsClientCreateOrUpdateResponse contains the response from method PrivateEndpointConnectionsClient.BeginCreateOrUpdate. +type PrivateEndpointConnectionsClientCreateOrUpdateResponse struct { + // An object that represents a private endpoint connection for a container registry. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientDeleteResponse contains the response from method PrivateEndpointConnectionsClient.BeginDelete. +type PrivateEndpointConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateEndpointConnectionsClientGetResponse contains the response from method PrivateEndpointConnectionsClient.Get. +type PrivateEndpointConnectionsClientGetResponse struct { + // An object that represents a private endpoint connection for a container registry. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientListResponse contains the response from method PrivateEndpointConnectionsClient.NewListPager. +type PrivateEndpointConnectionsClientListResponse struct { + // The result of a request to list private endpoint connections for a container registry. + PrivateEndpointConnectionListResult +} + +// RegistriesClientCheckNameAvailabilityResponse contains the response from method RegistriesClient.CheckNameAvailability. +type RegistriesClientCheckNameAvailabilityResponse struct { + // The result of a request to check the availability of a container registry name. + RegistryNameStatus +} + +// RegistriesClientCreateResponse contains the response from method RegistriesClient.BeginCreate. +type RegistriesClientCreateResponse struct { + // An object that represents a container registry. + Registry +} + +// RegistriesClientDeleteResponse contains the response from method RegistriesClient.BeginDelete. +type RegistriesClientDeleteResponse struct { + // placeholder for future response values +} + +// RegistriesClientGenerateCredentialsResponse contains the response from method RegistriesClient.BeginGenerateCredentials. +type RegistriesClientGenerateCredentialsResponse struct { + // The response from the GenerateCredentials operation. + GenerateCredentialsResult +} + +// RegistriesClientGetBuildSourceUploadURLResponse contains the response from method RegistriesClient.GetBuildSourceUploadURL. +type RegistriesClientGetBuildSourceUploadURLResponse struct { + // The properties of a response to source upload request. + SourceUploadDefinition +} + +// RegistriesClientGetPrivateLinkResourceResponse contains the response from method RegistriesClient.GetPrivateLinkResource. +type RegistriesClientGetPrivateLinkResourceResponse struct { + // A resource that supports private link capabilities. + PrivateLinkResource +} + +// RegistriesClientGetResponse contains the response from method RegistriesClient.Get. +type RegistriesClientGetResponse struct { + // An object that represents a container registry. + Registry +} + +// RegistriesClientImportImageResponse contains the response from method RegistriesClient.BeginImportImage. +type RegistriesClientImportImageResponse struct { + // placeholder for future response values +} + +// RegistriesClientListByResourceGroupResponse contains the response from method RegistriesClient.NewListByResourceGroupPager. +type RegistriesClientListByResourceGroupResponse struct { + // The result of a request to list container registries. + RegistryListResult +} + +// RegistriesClientListCredentialsResponse contains the response from method RegistriesClient.ListCredentials. +type RegistriesClientListCredentialsResponse struct { + // The response from the ListCredentials operation. + RegistryListCredentialsResult +} + +// RegistriesClientListPrivateLinkResourcesResponse contains the response from method RegistriesClient.NewListPrivateLinkResourcesPager. +type RegistriesClientListPrivateLinkResourcesResponse struct { + // The result of a request to list private link resources for a container registry. + PrivateLinkResourceListResult +} + +// RegistriesClientListResponse contains the response from method RegistriesClient.NewListPager. +type RegistriesClientListResponse struct { + // The result of a request to list container registries. + RegistryListResult +} + +// RegistriesClientListUsagesResponse contains the response from method RegistriesClient.ListUsages. +type RegistriesClientListUsagesResponse struct { + // The result of a request to get container registry quota usages. + RegistryUsageListResult +} + +// RegistriesClientRegenerateCredentialResponse contains the response from method RegistriesClient.RegenerateCredential. +type RegistriesClientRegenerateCredentialResponse struct { + // The response from the ListCredentials operation. + RegistryListCredentialsResult +} + +// RegistriesClientScheduleRunResponse contains the response from method RegistriesClient.BeginScheduleRun. +type RegistriesClientScheduleRunResponse struct { + // Run resource properties + Run +} + +// RegistriesClientUpdateResponse contains the response from method RegistriesClient.BeginUpdate. +type RegistriesClientUpdateResponse struct { + // An object that represents a container registry. + Registry +} + +// ReplicationsClientCreateResponse contains the response from method ReplicationsClient.BeginCreate. +type ReplicationsClientCreateResponse struct { + // An object that represents a replication for a container registry. + Replication +} + +// ReplicationsClientDeleteResponse contains the response from method ReplicationsClient.BeginDelete. +type ReplicationsClientDeleteResponse struct { + // placeholder for future response values +} + +// ReplicationsClientGetResponse contains the response from method ReplicationsClient.Get. +type ReplicationsClientGetResponse struct { + // An object that represents a replication for a container registry. + Replication +} + +// ReplicationsClientListResponse contains the response from method ReplicationsClient.NewListPager. +type ReplicationsClientListResponse struct { + // The result of a request to list replications for a container registry. + ReplicationListResult +} + +// ReplicationsClientUpdateResponse contains the response from method ReplicationsClient.BeginUpdate. +type ReplicationsClientUpdateResponse struct { + // An object that represents a replication for a container registry. + Replication +} + +// RunsClientCancelResponse contains the response from method RunsClient.BeginCancel. +type RunsClientCancelResponse struct { + // placeholder for future response values +} + +// RunsClientGetLogSasURLResponse contains the response from method RunsClient.GetLogSasURL. +type RunsClientGetLogSasURLResponse struct { + // The result of get log link operation. + RunGetLogResult +} + +// RunsClientGetResponse contains the response from method RunsClient.Get. +type RunsClientGetResponse struct { + // Run resource properties + Run +} + +// RunsClientListResponse contains the response from method RunsClient.NewListPager. +type RunsClientListResponse struct { + // Collection of runs. + RunListResult +} + +// RunsClientUpdateResponse contains the response from method RunsClient.BeginUpdate. +type RunsClientUpdateResponse struct { + // Run resource properties + Run +} + +// ScopeMapsClientCreateResponse contains the response from method ScopeMapsClient.BeginCreate. +type ScopeMapsClientCreateResponse struct { + // An object that represents a scope map for a container registry. + ScopeMap +} + +// ScopeMapsClientDeleteResponse contains the response from method ScopeMapsClient.BeginDelete. +type ScopeMapsClientDeleteResponse struct { + // placeholder for future response values +} + +// ScopeMapsClientGetResponse contains the response from method ScopeMapsClient.Get. +type ScopeMapsClientGetResponse struct { + // An object that represents a scope map for a container registry. + ScopeMap +} + +// ScopeMapsClientListResponse contains the response from method ScopeMapsClient.NewListPager. +type ScopeMapsClientListResponse struct { + // The result of a request to list scope maps for a container registry. + ScopeMapListResult +} + +// ScopeMapsClientUpdateResponse contains the response from method ScopeMapsClient.BeginUpdate. +type ScopeMapsClientUpdateResponse struct { + // An object that represents a scope map for a container registry. + ScopeMap +} + +// TaskRunsClientCreateResponse contains the response from method TaskRunsClient.BeginCreate. +type TaskRunsClientCreateResponse struct { + // The task run that has the ARM resource and properties. + // The task run will have the information of request and result of a run. + TaskRun +} + +// TaskRunsClientDeleteResponse contains the response from method TaskRunsClient.BeginDelete. +type TaskRunsClientDeleteResponse struct { + // placeholder for future response values +} + +// TaskRunsClientGetDetailsResponse contains the response from method TaskRunsClient.GetDetails. +type TaskRunsClientGetDetailsResponse struct { + // The task run that has the ARM resource and properties. + // The task run will have the information of request and result of a run. + TaskRun +} + +// TaskRunsClientGetResponse contains the response from method TaskRunsClient.Get. +type TaskRunsClientGetResponse struct { + // The task run that has the ARM resource and properties. + // The task run will have the information of request and result of a run. + TaskRun +} + +// TaskRunsClientListResponse contains the response from method TaskRunsClient.NewListPager. +type TaskRunsClientListResponse struct { + // The collection of task runs. + TaskRunListResult +} + +// TaskRunsClientUpdateResponse contains the response from method TaskRunsClient.BeginUpdate. +type TaskRunsClientUpdateResponse struct { + // The task run that has the ARM resource and properties. + // The task run will have the information of request and result of a run. + TaskRun +} + +// TasksClientCreateResponse contains the response from method TasksClient.BeginCreate. +type TasksClientCreateResponse struct { + // The task that has the ARM resource and task properties. + // The task will have all information to schedule a run against it. + Task +} + +// TasksClientDeleteResponse contains the response from method TasksClient.BeginDelete. +type TasksClientDeleteResponse struct { + // placeholder for future response values +} + +// TasksClientGetDetailsResponse contains the response from method TasksClient.GetDetails. +type TasksClientGetDetailsResponse struct { + // The task that has the ARM resource and task properties. + // The task will have all information to schedule a run against it. + Task +} + +// TasksClientGetResponse contains the response from method TasksClient.Get. +type TasksClientGetResponse struct { + // The task that has the ARM resource and task properties. + // The task will have all information to schedule a run against it. + Task +} + +// TasksClientListResponse contains the response from method TasksClient.NewListPager. +type TasksClientListResponse struct { + // The collection of tasks. + TaskListResult +} + +// TasksClientUpdateResponse contains the response from method TasksClient.BeginUpdate. +type TasksClientUpdateResponse struct { + // The task that has the ARM resource and task properties. + // The task will have all information to schedule a run against it. + Task +} + +// TokensClientCreateResponse contains the response from method TokensClient.BeginCreate. +type TokensClientCreateResponse struct { + // An object that represents a token for a container registry. + Token +} + +// TokensClientDeleteResponse contains the response from method TokensClient.BeginDelete. +type TokensClientDeleteResponse struct { + // placeholder for future response values +} + +// TokensClientGetResponse contains the response from method TokensClient.Get. +type TokensClientGetResponse struct { + // An object that represents a token for a container registry. + Token +} + +// TokensClientListResponse contains the response from method TokensClient.NewListPager. +type TokensClientListResponse struct { + // The result of a request to list tokens for a container registry. + TokenListResult +} + +// TokensClientUpdateResponse contains the response from method TokensClient.BeginUpdate. +type TokensClientUpdateResponse struct { + // An object that represents a token for a container registry. + Token +} + +// WebhooksClientCreateResponse contains the response from method WebhooksClient.BeginCreate. +type WebhooksClientCreateResponse struct { + // An object that represents a webhook for a container registry. + Webhook +} + +// WebhooksClientDeleteResponse contains the response from method WebhooksClient.BeginDelete. +type WebhooksClientDeleteResponse struct { + // placeholder for future response values +} + +// WebhooksClientGetCallbackConfigResponse contains the response from method WebhooksClient.GetCallbackConfig. +type WebhooksClientGetCallbackConfigResponse struct { + // The configuration of service URI and custom headers for the webhook. + CallbackConfig +} + +// WebhooksClientGetResponse contains the response from method WebhooksClient.Get. +type WebhooksClientGetResponse struct { + // An object that represents a webhook for a container registry. + Webhook +} + +// WebhooksClientListEventsResponse contains the response from method WebhooksClient.NewListEventsPager. +type WebhooksClientListEventsResponse struct { + // The result of a request to list events for a webhook. + EventListResult +} + +// WebhooksClientListResponse contains the response from method WebhooksClient.NewListPager. +type WebhooksClientListResponse struct { + // The result of a request to list webhooks for a container registry. + WebhookListResult +} + +// WebhooksClientPingResponse contains the response from method WebhooksClient.Ping. +type WebhooksClientPingResponse struct { + // The basic information of an event. + EventInfo +} + +// WebhooksClientUpdateResponse contains the response from method WebhooksClient.BeginUpdate. +type WebhooksClientUpdateResponse struct { + // An object that represents a webhook for a container registry. + Webhook +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/runs_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/runs_client.go new file mode 100644 index 0000000000..a76c963053 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/runs_client.go @@ -0,0 +1,417 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// RunsClient contains the methods for the Runs group. +// Don't use this type directly, use NewRunsClient() instead. +type RunsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRunsClient creates a new instance of RunsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewRunsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RunsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RunsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCancel - Cancel an existing run. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - runID - The run ID. +// - options - RunsClientBeginCancelOptions contains the optional parameters for the RunsClient.BeginCancel method. +func (client *RunsClient) BeginCancel(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientBeginCancelOptions) (*runtime.Poller[RunsClientCancelResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.cancel(ctx, resourceGroupName, registryName, runID, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RunsClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RunsClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Cancel - Cancel an existing run. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *RunsClient) cancel(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientBeginCancelOptions) (*http.Response, error) { + var err error + const operationName = "RunsClient.BeginCancel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCreateRequest(ctx, resourceGroupName, registryName, runID, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// cancelCreateRequest creates the Cancel request. +func (client *RunsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientBeginCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/runs/{runId}/cancel" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if runID == "" { + return nil, errors.New("parameter runID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runId}", url.PathEscape(runID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the detailed information for a given run. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - runID - The run ID. +// - options - RunsClientGetOptions contains the optional parameters for the RunsClient.Get method. +func (client *RunsClient) Get(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientGetOptions) (RunsClientGetResponse, error) { + var err error + const operationName = "RunsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, runID, options) + if err != nil { + return RunsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RunsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RunsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RunsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/runs/{runId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if runID == "" { + return nil, errors.New("parameter runID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runId}", url.PathEscape(runID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RunsClient) getHandleResponse(resp *http.Response) (RunsClientGetResponse, error) { + result := RunsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Run); err != nil { + return RunsClientGetResponse{}, err + } + return result, nil +} + +// GetLogSasURL - Gets a link to download the run logs. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - runID - The run ID. +// - options - RunsClientGetLogSasURLOptions contains the optional parameters for the RunsClient.GetLogSasURL method. +func (client *RunsClient) GetLogSasURL(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientGetLogSasURLOptions) (RunsClientGetLogSasURLResponse, error) { + var err error + const operationName = "RunsClient.GetLogSasURL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getLogSasURLCreateRequest(ctx, resourceGroupName, registryName, runID, options) + if err != nil { + return RunsClientGetLogSasURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RunsClientGetLogSasURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RunsClientGetLogSasURLResponse{}, err + } + resp, err := client.getLogSasURLHandleResponse(httpResp) + return resp, err +} + +// getLogSasURLCreateRequest creates the GetLogSasURL request. +func (client *RunsClient) getLogSasURLCreateRequest(ctx context.Context, resourceGroupName string, registryName string, runID string, options *RunsClientGetLogSasURLOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/runs/{runId}/listLogSasUrl" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if runID == "" { + return nil, errors.New("parameter runID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runId}", url.PathEscape(runID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getLogSasURLHandleResponse handles the GetLogSasURL response. +func (client *RunsClient) getLogSasURLHandleResponse(resp *http.Response) (RunsClientGetLogSasURLResponse, error) { + result := RunsClientGetLogSasURLResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RunGetLogResult); err != nil { + return RunsClientGetLogSasURLResponse{}, err + } + return result, nil +} + +// NewListPager - Gets all the runs for a registry. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - options - RunsClientListOptions contains the optional parameters for the RunsClient.NewListPager method. +func (client *RunsClient) NewListPager(resourceGroupName string, registryName string, options *RunsClientListOptions) *runtime.Pager[RunsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RunsClientListResponse]{ + More: func(page RunsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RunsClientListResponse) (RunsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RunsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return RunsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RunsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *RunsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/runs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RunsClient) listHandleResponse(resp *http.Response) (RunsClientListResponse, error) { + result := RunsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RunListResult); err != nil { + return RunsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Patch the run properties. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - runID - The run ID. +// - runUpdateParameters - The run update properties. +// - options - RunsClientBeginUpdateOptions contains the optional parameters for the RunsClient.BeginUpdate method. +func (client *RunsClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, runID string, runUpdateParameters RunUpdateParameters, options *RunsClientBeginUpdateOptions) (*runtime.Poller[RunsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, runID, runUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RunsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RunsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Patch the run properties. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *RunsClient) update(ctx context.Context, resourceGroupName string, registryName string, runID string, runUpdateParameters RunUpdateParameters, options *RunsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "RunsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, runID, runUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *RunsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, runID string, runUpdateParameters RunUpdateParameters, options *RunsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/runs/{runId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if runID == "" { + return nil, errors.New("parameter runID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{runId}", url.PathEscape(runID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, runUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/scopemaps_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/scopemaps_client.go new file mode 100644 index 0000000000..cff215097a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/scopemaps_client.go @@ -0,0 +1,428 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ScopeMapsClient contains the methods for the ScopeMaps group. +// Don't use this type directly, use NewScopeMapsClient() instead. +type ScopeMapsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewScopeMapsClient creates a new instance of ScopeMapsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewScopeMapsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ScopeMapsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ScopeMapsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a scope map for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - scopeMapName - The name of the scope map. +// - scopeMapCreateParameters - The parameters for creating a scope map. +// - options - ScopeMapsClientBeginCreateOptions contains the optional parameters for the ScopeMapsClient.BeginCreate method. +func (client *ScopeMapsClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, scopeMapCreateParameters ScopeMap, options *ScopeMapsClientBeginCreateOptions) (*runtime.Poller[ScopeMapsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, scopeMapName, scopeMapCreateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ScopeMapsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ScopeMapsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a scope map for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ScopeMapsClient) create(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, scopeMapCreateParameters ScopeMap, options *ScopeMapsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "ScopeMapsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, scopeMapName, scopeMapCreateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *ScopeMapsClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, scopeMapCreateParameters ScopeMap, options *ScopeMapsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if scopeMapName == "" { + return nil, errors.New("parameter scopeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeMapName}", url.PathEscape(scopeMapName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, scopeMapCreateParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a scope map from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - scopeMapName - The name of the scope map. +// - options - ScopeMapsClientBeginDeleteOptions contains the optional parameters for the ScopeMapsClient.BeginDelete method. +func (client *ScopeMapsClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, options *ScopeMapsClientBeginDeleteOptions) (*runtime.Poller[ScopeMapsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, scopeMapName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ScopeMapsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ScopeMapsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a scope map from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ScopeMapsClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, options *ScopeMapsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ScopeMapsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, scopeMapName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ScopeMapsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, options *ScopeMapsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if scopeMapName == "" { + return nil, errors.New("parameter scopeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeMapName}", url.PathEscape(scopeMapName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the properties of the specified scope map. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - scopeMapName - The name of the scope map. +// - options - ScopeMapsClientGetOptions contains the optional parameters for the ScopeMapsClient.Get method. +func (client *ScopeMapsClient) Get(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, options *ScopeMapsClientGetOptions) (ScopeMapsClientGetResponse, error) { + var err error + const operationName = "ScopeMapsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, scopeMapName, options) + if err != nil { + return ScopeMapsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScopeMapsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScopeMapsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScopeMapsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, options *ScopeMapsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if scopeMapName == "" { + return nil, errors.New("parameter scopeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeMapName}", url.PathEscape(scopeMapName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScopeMapsClient) getHandleResponse(resp *http.Response) (ScopeMapsClientGetResponse, error) { + result := ScopeMapsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScopeMap); err != nil { + return ScopeMapsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the scope maps for the specified container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - ScopeMapsClientListOptions contains the optional parameters for the ScopeMapsClient.NewListPager method. +func (client *ScopeMapsClient) NewListPager(resourceGroupName string, registryName string, options *ScopeMapsClientListOptions) *runtime.Pager[ScopeMapsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ScopeMapsClientListResponse]{ + More: func(page ScopeMapsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ScopeMapsClientListResponse) (ScopeMapsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScopeMapsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return ScopeMapsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ScopeMapsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *ScopeMapsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ScopeMapsClient) listHandleResponse(resp *http.Response) (ScopeMapsClientListResponse, error) { + result := ScopeMapsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScopeMapListResult); err != nil { + return ScopeMapsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a scope map with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - scopeMapName - The name of the scope map. +// - scopeMapUpdateParameters - The parameters for updating a scope map. +// - options - ScopeMapsClientBeginUpdateOptions contains the optional parameters for the ScopeMapsClient.BeginUpdate method. +func (client *ScopeMapsClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, scopeMapUpdateParameters ScopeMapUpdateParameters, options *ScopeMapsClientBeginUpdateOptions) (*runtime.Poller[ScopeMapsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, scopeMapName, scopeMapUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ScopeMapsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ScopeMapsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a scope map with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ScopeMapsClient) update(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, scopeMapUpdateParameters ScopeMapUpdateParameters, options *ScopeMapsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ScopeMapsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, scopeMapName, scopeMapUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ScopeMapsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, scopeMapName string, scopeMapUpdateParameters ScopeMapUpdateParameters, options *ScopeMapsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if scopeMapName == "" { + return nil, errors.New("parameter scopeMapName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scopeMapName}", url.PathEscape(scopeMapName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, scopeMapUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/taskruns_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/taskruns_client.go new file mode 100644 index 0000000000..16f8e5d749 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/taskruns_client.go @@ -0,0 +1,494 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TaskRunsClient contains the methods for the TaskRuns group. +// Don't use this type directly, use NewTaskRunsClient() instead. +type TaskRunsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTaskRunsClient creates a new instance of TaskRunsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTaskRunsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TaskRunsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TaskRunsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a task run for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskRunName - The name of the task run. +// - taskRun - The parameters of a run that needs to scheduled. +// - options - TaskRunsClientBeginCreateOptions contains the optional parameters for the TaskRunsClient.BeginCreate method. +func (client *TaskRunsClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, taskRun TaskRun, options *TaskRunsClientBeginCreateOptions) (*runtime.Poller[TaskRunsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, taskRunName, taskRun, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TaskRunsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TaskRunsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a task run for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *TaskRunsClient) create(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, taskRun TaskRun, options *TaskRunsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "TaskRunsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, taskRunName, taskRun, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *TaskRunsClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, taskRun TaskRun, options *TaskRunsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns/{taskRunName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskRunName == "" { + return nil, errors.New("parameter taskRunName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskRunName}", url.PathEscape(taskRunName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, taskRun); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a specified task run resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskRunName - The name of the task run. +// - options - TaskRunsClientBeginDeleteOptions contains the optional parameters for the TaskRunsClient.BeginDelete method. +func (client *TaskRunsClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientBeginDeleteOptions) (*runtime.Poller[TaskRunsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, taskRunName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TaskRunsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TaskRunsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a specified task run resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *TaskRunsClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "TaskRunsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, taskRunName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TaskRunsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns/{taskRunName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskRunName == "" { + return nil, errors.New("parameter taskRunName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskRunName}", url.PathEscape(taskRunName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the detailed information for a given task run. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskRunName - The name of the task run. +// - options - TaskRunsClientGetOptions contains the optional parameters for the TaskRunsClient.Get method. +func (client *TaskRunsClient) Get(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientGetOptions) (TaskRunsClientGetResponse, error) { + var err error + const operationName = "TaskRunsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, taskRunName, options) + if err != nil { + return TaskRunsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TaskRunsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TaskRunsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TaskRunsClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns/{taskRunName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskRunName == "" { + return nil, errors.New("parameter taskRunName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskRunName}", url.PathEscape(taskRunName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TaskRunsClient) getHandleResponse(resp *http.Response) (TaskRunsClientGetResponse, error) { + result := TaskRunsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TaskRun); err != nil { + return TaskRunsClientGetResponse{}, err + } + return result, nil +} + +// GetDetails - Gets the detailed information for a given task run that includes all secrets. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskRunName - The name of the task run. +// - options - TaskRunsClientGetDetailsOptions contains the optional parameters for the TaskRunsClient.GetDetails method. +func (client *TaskRunsClient) GetDetails(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientGetDetailsOptions) (TaskRunsClientGetDetailsResponse, error) { + var err error + const operationName = "TaskRunsClient.GetDetails" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDetailsCreateRequest(ctx, resourceGroupName, registryName, taskRunName, options) + if err != nil { + return TaskRunsClientGetDetailsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TaskRunsClientGetDetailsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TaskRunsClientGetDetailsResponse{}, err + } + resp, err := client.getDetailsHandleResponse(httpResp) + return resp, err +} + +// getDetailsCreateRequest creates the GetDetails request. +func (client *TaskRunsClient) getDetailsCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientGetDetailsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns/{taskRunName}/listDetails" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskRunName == "" { + return nil, errors.New("parameter taskRunName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskRunName}", url.PathEscape(taskRunName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDetailsHandleResponse handles the GetDetails response. +func (client *TaskRunsClient) getDetailsHandleResponse(resp *http.Response) (TaskRunsClientGetDetailsResponse, error) { + result := TaskRunsClientGetDetailsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TaskRun); err != nil { + return TaskRunsClientGetDetailsResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the task runs for a specified container registry. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - options - TaskRunsClientListOptions contains the optional parameters for the TaskRunsClient.NewListPager method. +func (client *TaskRunsClient) NewListPager(resourceGroupName string, registryName string, options *TaskRunsClientListOptions) *runtime.Pager[TaskRunsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TaskRunsClientListResponse]{ + More: func(page TaskRunsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TaskRunsClientListResponse) (TaskRunsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TaskRunsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return TaskRunsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TaskRunsClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *TaskRunsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TaskRunsClient) listHandleResponse(resp *http.Response) (TaskRunsClientListResponse, error) { + result := TaskRunsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TaskRunListResult); err != nil { + return TaskRunsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a task run with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskRunName - The name of the task run. +// - updateParameters - The parameters for updating a task run. +// - options - TaskRunsClientBeginUpdateOptions contains the optional parameters for the TaskRunsClient.BeginUpdate method. +func (client *TaskRunsClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, updateParameters TaskRunUpdateParameters, options *TaskRunsClientBeginUpdateOptions) (*runtime.Poller[TaskRunsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, taskRunName, updateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TaskRunsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TaskRunsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a task run with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *TaskRunsClient) update(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, updateParameters TaskRunUpdateParameters, options *TaskRunsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "TaskRunsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, taskRunName, updateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *TaskRunsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, updateParameters TaskRunUpdateParameters, options *TaskRunsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns/{taskRunName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskRunName == "" { + return nil, errors.New("parameter taskRunName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskRunName}", url.PathEscape(taskRunName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, updateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tasks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tasks_client.go new file mode 100644 index 0000000000..29aaec5a17 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tasks_client.go @@ -0,0 +1,494 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TasksClient contains the methods for the Tasks group. +// Don't use this type directly, use NewTasksClient() instead. +type TasksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTasksClient creates a new instance of TasksClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTasksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TasksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TasksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a task for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskName - The name of the container registry task. +// - taskCreateParameters - The parameters for creating a task. +// - options - TasksClientBeginCreateOptions contains the optional parameters for the TasksClient.BeginCreate method. +func (client *TasksClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, taskName string, taskCreateParameters Task, options *TasksClientBeginCreateOptions) (*runtime.Poller[TasksClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, taskName, taskCreateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TasksClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TasksClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a task for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *TasksClient) create(ctx context.Context, resourceGroupName string, registryName string, taskName string, taskCreateParameters Task, options *TasksClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "TasksClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, taskName, taskCreateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *TasksClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskName string, taskCreateParameters Task, options *TasksClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tasks/{taskName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskName == "" { + return nil, errors.New("parameter taskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskName}", url.PathEscape(taskName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, taskCreateParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a specified task. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskName - The name of the container registry task. +// - options - TasksClientBeginDeleteOptions contains the optional parameters for the TasksClient.BeginDelete method. +func (client *TasksClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientBeginDeleteOptions) (*runtime.Poller[TasksClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, taskName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TasksClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TasksClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a specified task. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *TasksClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "TasksClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, taskName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TasksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tasks/{taskName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskName == "" { + return nil, errors.New("parameter taskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskName}", url.PathEscape(taskName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get the properties of a specified task. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskName - The name of the container registry task. +// - options - TasksClientGetOptions contains the optional parameters for the TasksClient.Get method. +func (client *TasksClient) Get(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientGetOptions) (TasksClientGetResponse, error) { + var err error + const operationName = "TasksClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, taskName, options) + if err != nil { + return TasksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TasksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TasksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TasksClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tasks/{taskName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskName == "" { + return nil, errors.New("parameter taskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskName}", url.PathEscape(taskName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TasksClient) getHandleResponse(resp *http.Response) (TasksClientGetResponse, error) { + result := TasksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Task); err != nil { + return TasksClientGetResponse{}, err + } + return result, nil +} + +// GetDetails - Returns a task with extended information that includes all secrets. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskName - The name of the container registry task. +// - options - TasksClientGetDetailsOptions contains the optional parameters for the TasksClient.GetDetails method. +func (client *TasksClient) GetDetails(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientGetDetailsOptions) (TasksClientGetDetailsResponse, error) { + var err error + const operationName = "TasksClient.GetDetails" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDetailsCreateRequest(ctx, resourceGroupName, registryName, taskName, options) + if err != nil { + return TasksClientGetDetailsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TasksClientGetDetailsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TasksClientGetDetailsResponse{}, err + } + resp, err := client.getDetailsHandleResponse(httpResp) + return resp, err +} + +// getDetailsCreateRequest creates the GetDetails request. +func (client *TasksClient) getDetailsCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskName string, options *TasksClientGetDetailsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tasks/{taskName}/listDetails" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskName == "" { + return nil, errors.New("parameter taskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskName}", url.PathEscape(taskName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDetailsHandleResponse handles the GetDetails response. +func (client *TasksClient) getDetailsHandleResponse(resp *http.Response) (TasksClientGetDetailsResponse, error) { + result := TasksClientGetDetailsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Task); err != nil { + return TasksClientGetDetailsResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the tasks for a specified container registry. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - options - TasksClientListOptions contains the optional parameters for the TasksClient.NewListPager method. +func (client *TasksClient) NewListPager(resourceGroupName string, registryName string, options *TasksClientListOptions) *runtime.Pager[TasksClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TasksClientListResponse]{ + More: func(page TasksClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TasksClientListResponse) (TasksClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TasksClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return TasksClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TasksClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *TasksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tasks" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TasksClient) listHandleResponse(resp *http.Response) (TasksClientListResponse, error) { + result := TasksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TaskListResult); err != nil { + return TasksClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a task with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +// - resourceGroupName - The name of the resource group to which the container registry belongs. +// - registryName - The name of the container registry. +// - taskName - The name of the container registry task. +// - taskUpdateParameters - The parameters for updating a task. +// - options - TasksClientBeginUpdateOptions contains the optional parameters for the TasksClient.BeginUpdate method. +func (client *TasksClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, taskName string, taskUpdateParameters TaskUpdateParameters, options *TasksClientBeginUpdateOptions) (*runtime.Poller[TasksClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, taskName, taskUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TasksClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TasksClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a task with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2019-06-01-preview +func (client *TasksClient) update(ctx context.Context, resourceGroupName string, registryName string, taskName string, taskUpdateParameters TaskUpdateParameters, options *TasksClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "TasksClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, taskName, taskUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *TasksClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskName string, taskUpdateParameters TaskUpdateParameters, options *TasksClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tasks/{taskName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if taskName == "" { + return nil, errors.New("parameter taskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{taskName}", url.PathEscape(taskName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, taskUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/time_rfc3339.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/time_rfc3339.go new file mode 100644 index 0000000000..7d52c939bb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/time_rfc3339.go @@ -0,0 +1,86 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +const ( + utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` + utcDateTime = "2006-01-02T15:04:05.999999999" + dateTimeJSON = `"` + time.RFC3339Nano + `"` +) + +type dateTimeRFC3339 time.Time + +func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t dateTimeRFC3339) MarshalText() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcDateTimeJSON + if tzOffsetRegex.Match(data) { + layout = dateTimeJSON + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { + layout := utcDateTime + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = dateTimeRFC3339(p) + return err +} + +func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*dateTimeRFC3339)(t) +} + +func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || strings.EqualFold(string(data), "null") { + return nil + } + var aux dateTimeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tokens_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tokens_client.go new file mode 100644 index 0000000000..27274babc5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/tokens_client.go @@ -0,0 +1,428 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TokensClient contains the methods for the Tokens group. +// Don't use this type directly, use NewTokensClient() instead. +type TokensClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTokensClient creates a new instance of TokensClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTokensClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TokensClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TokensClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a token for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - tokenName - The name of the token. +// - tokenCreateParameters - The parameters for creating a token. +// - options - TokensClientBeginCreateOptions contains the optional parameters for the TokensClient.BeginCreate method. +func (client *TokensClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, tokenName string, tokenCreateParameters Token, options *TokensClientBeginCreateOptions) (*runtime.Poller[TokensClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, tokenName, tokenCreateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TokensClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TokensClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a token for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *TokensClient) create(ctx context.Context, resourceGroupName string, registryName string, tokenName string, tokenCreateParameters Token, options *TokensClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "TokensClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, tokenName, tokenCreateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *TokensClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, tokenName string, tokenCreateParameters Token, options *TokensClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tokens/{tokenName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if tokenName == "" { + return nil, errors.New("parameter tokenName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tokenName}", url.PathEscape(tokenName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tokenCreateParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a token from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - tokenName - The name of the token. +// - options - TokensClientBeginDeleteOptions contains the optional parameters for the TokensClient.BeginDelete method. +func (client *TokensClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, tokenName string, options *TokensClientBeginDeleteOptions) (*runtime.Poller[TokensClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, tokenName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TokensClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TokensClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a token from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *TokensClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, tokenName string, options *TokensClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "TokensClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, tokenName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TokensClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, tokenName string, options *TokensClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tokens/{tokenName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if tokenName == "" { + return nil, errors.New("parameter tokenName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tokenName}", url.PathEscape(tokenName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the properties of the specified token. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - tokenName - The name of the token. +// - options - TokensClientGetOptions contains the optional parameters for the TokensClient.Get method. +func (client *TokensClient) Get(ctx context.Context, resourceGroupName string, registryName string, tokenName string, options *TokensClientGetOptions) (TokensClientGetResponse, error) { + var err error + const operationName = "TokensClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, tokenName, options) + if err != nil { + return TokensClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TokensClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TokensClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TokensClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, tokenName string, options *TokensClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tokens/{tokenName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if tokenName == "" { + return nil, errors.New("parameter tokenName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tokenName}", url.PathEscape(tokenName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TokensClient) getHandleResponse(resp *http.Response) (TokensClientGetResponse, error) { + result := TokensClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Token); err != nil { + return TokensClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the tokens for the specified container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - TokensClientListOptions contains the optional parameters for the TokensClient.NewListPager method. +func (client *TokensClient) NewListPager(resourceGroupName string, registryName string, options *TokensClientListOptions) *runtime.Pager[TokensClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TokensClientListResponse]{ + More: func(page TokensClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TokensClientListResponse) (TokensClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TokensClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return TokensClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TokensClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *TokensClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tokens" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TokensClient) listHandleResponse(resp *http.Response) (TokensClientListResponse, error) { + result := TokensClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TokenListResult); err != nil { + return TokensClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a token with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - tokenName - The name of the token. +// - tokenUpdateParameters - The parameters for updating a token. +// - options - TokensClientBeginUpdateOptions contains the optional parameters for the TokensClient.BeginUpdate method. +func (client *TokensClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, tokenName string, tokenUpdateParameters TokenUpdateParameters, options *TokensClientBeginUpdateOptions) (*runtime.Poller[TokensClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, tokenName, tokenUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TokensClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TokensClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a token with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *TokensClient) update(ctx context.Context, resourceGroupName string, registryName string, tokenName string, tokenUpdateParameters TokenUpdateParameters, options *TokensClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "TokensClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, tokenName, tokenUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *TokensClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, tokenName string, tokenUpdateParameters TokenUpdateParameters, options *TokensClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/tokens/{tokenName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if tokenName == "" { + return nil, errors.New("parameter tokenName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tokenName}", url.PathEscape(tokenName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tokenUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/webhooks_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/webhooks_client.go new file mode 100644 index 0000000000..9ee0845d20 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry/webhooks_client.go @@ -0,0 +1,635 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcontainerregistry + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// WebhooksClient contains the methods for the Webhooks group. +// Don't use this type directly, use NewWebhooksClient() instead. +type WebhooksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWebhooksClient creates a new instance of WebhooksClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewWebhooksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WebhooksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WebhooksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Creates a webhook for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - webhookCreateParameters - The parameters for creating a webhook. +// - options - WebhooksClientBeginCreateOptions contains the optional parameters for the WebhooksClient.BeginCreate method. +func (client *WebhooksClient) BeginCreate(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookCreateParameters WebhookCreateParameters, options *WebhooksClientBeginCreateOptions) (*runtime.Poller[WebhooksClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, registryName, webhookName, webhookCreateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WebhooksClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WebhooksClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Creates a webhook for a container registry with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *WebhooksClient) create(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookCreateParameters WebhookCreateParameters, options *WebhooksClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "WebhooksClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, registryName, webhookName, webhookCreateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *WebhooksClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookCreateParameters WebhookCreateParameters, options *WebhooksClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, webhookCreateParameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a webhook from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - options - WebhooksClientBeginDeleteOptions contains the optional parameters for the WebhooksClient.BeginDelete method. +func (client *WebhooksClient) BeginDelete(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientBeginDeleteOptions) (*runtime.Poller[WebhooksClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, registryName, webhookName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WebhooksClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WebhooksClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a webhook from a container registry. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *WebhooksClient) deleteOperation(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "WebhooksClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, registryName, webhookName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *WebhooksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Gets the properties of the specified webhook. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - options - WebhooksClientGetOptions contains the optional parameters for the WebhooksClient.Get method. +func (client *WebhooksClient) Get(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientGetOptions) (WebhooksClientGetResponse, error) { + var err error + const operationName = "WebhooksClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, registryName, webhookName, options) + if err != nil { + return WebhooksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WebhooksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WebhooksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WebhooksClient) getCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WebhooksClient) getHandleResponse(resp *http.Response) (WebhooksClientGetResponse, error) { + result := WebhooksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Webhook); err != nil { + return WebhooksClientGetResponse{}, err + } + return result, nil +} + +// GetCallbackConfig - Gets the configuration of service URI and custom headers for the webhook. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - options - WebhooksClientGetCallbackConfigOptions contains the optional parameters for the WebhooksClient.GetCallbackConfig +// method. +func (client *WebhooksClient) GetCallbackConfig(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientGetCallbackConfigOptions) (WebhooksClientGetCallbackConfigResponse, error) { + var err error + const operationName = "WebhooksClient.GetCallbackConfig" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCallbackConfigCreateRequest(ctx, resourceGroupName, registryName, webhookName, options) + if err != nil { + return WebhooksClientGetCallbackConfigResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WebhooksClientGetCallbackConfigResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WebhooksClientGetCallbackConfigResponse{}, err + } + resp, err := client.getCallbackConfigHandleResponse(httpResp) + return resp, err +} + +// getCallbackConfigCreateRequest creates the GetCallbackConfig request. +func (client *WebhooksClient) getCallbackConfigCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientGetCallbackConfigOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}/getCallbackConfig" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getCallbackConfigHandleResponse handles the GetCallbackConfig response. +func (client *WebhooksClient) getCallbackConfigHandleResponse(resp *http.Response) (WebhooksClientGetCallbackConfigResponse, error) { + result := WebhooksClientGetCallbackConfigResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CallbackConfig); err != nil { + return WebhooksClientGetCallbackConfigResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the webhooks for the specified container registry. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - options - WebhooksClientListOptions contains the optional parameters for the WebhooksClient.NewListPager method. +func (client *WebhooksClient) NewListPager(resourceGroupName string, registryName string, options *WebhooksClientListOptions) *runtime.Pager[WebhooksClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[WebhooksClientListResponse]{ + More: func(page WebhooksClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WebhooksClientListResponse) (WebhooksClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WebhooksClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, registryName, options) + }, nil) + if err != nil { + return WebhooksClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *WebhooksClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *WebhooksClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *WebhooksClient) listHandleResponse(resp *http.Response) (WebhooksClientListResponse, error) { + result := WebhooksClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WebhookListResult); err != nil { + return WebhooksClientListResponse{}, err + } + return result, nil +} + +// NewListEventsPager - Lists recent events for the specified webhook. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - options - WebhooksClientListEventsOptions contains the optional parameters for the WebhooksClient.NewListEventsPager method. +func (client *WebhooksClient) NewListEventsPager(resourceGroupName string, registryName string, webhookName string, options *WebhooksClientListEventsOptions) *runtime.Pager[WebhooksClientListEventsResponse] { + return runtime.NewPager(runtime.PagingHandler[WebhooksClientListEventsResponse]{ + More: func(page WebhooksClientListEventsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WebhooksClientListEventsResponse) (WebhooksClientListEventsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WebhooksClient.NewListEventsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listEventsCreateRequest(ctx, resourceGroupName, registryName, webhookName, options) + }, nil) + if err != nil { + return WebhooksClientListEventsResponse{}, err + } + return client.listEventsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listEventsCreateRequest creates the ListEvents request. +func (client *WebhooksClient) listEventsCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientListEventsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}/listEvents" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listEventsHandleResponse handles the ListEvents response. +func (client *WebhooksClient) listEventsHandleResponse(resp *http.Response) (WebhooksClientListEventsResponse, error) { + result := WebhooksClientListEventsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EventListResult); err != nil { + return WebhooksClientListEventsResponse{}, err + } + return result, nil +} + +// Ping - Triggers a ping event to be sent to the webhook. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - options - WebhooksClientPingOptions contains the optional parameters for the WebhooksClient.Ping method. +func (client *WebhooksClient) Ping(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientPingOptions) (WebhooksClientPingResponse, error) { + var err error + const operationName = "WebhooksClient.Ping" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.pingCreateRequest(ctx, resourceGroupName, registryName, webhookName, options) + if err != nil { + return WebhooksClientPingResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WebhooksClientPingResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WebhooksClientPingResponse{}, err + } + resp, err := client.pingHandleResponse(httpResp) + return resp, err +} + +// pingCreateRequest creates the Ping request. +func (client *WebhooksClient) pingCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientPingOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}/ping" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// pingHandleResponse handles the Ping response. +func (client *WebhooksClient) pingHandleResponse(resp *http.Response) (WebhooksClientPingResponse, error) { + result := WebhooksClientPingResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EventInfo); err != nil { + return WebhooksClientPingResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a webhook with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - registryName - The name of the container registry. +// - webhookName - The name of the webhook. +// - webhookUpdateParameters - The parameters for updating a webhook. +// - options - WebhooksClientBeginUpdateOptions contains the optional parameters for the WebhooksClient.BeginUpdate method. +func (client *WebhooksClient) BeginUpdate(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookUpdateParameters WebhookUpdateParameters, options *WebhooksClientBeginUpdateOptions) (*runtime.Poller[WebhooksClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, registryName, webhookName, webhookUpdateParameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WebhooksClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WebhooksClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a webhook with the specified parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *WebhooksClient) update(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookUpdateParameters WebhookUpdateParameters, options *WebhooksClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "WebhooksClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, registryName, webhookName, webhookUpdateParameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *WebhooksClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookUpdateParameters WebhookUpdateParameters, options *WebhooksClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if registryName == "" { + return nil, errors.New("parameter registryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{registryName}", url.PathEscape(registryName)) + if webhookName == "" { + return nil, errors.New("parameter webhookName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{webhookName}", url.PathEscape(webhookName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, webhookUpdateParameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md index b18a12306a..24cef13efe 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/CHANGELOG.md @@ -1,5 +1,152 @@ # Release History +## 4.4.0 (2023-10-27) +### Features Added + +- New enum type `IstioIngressGatewayMode` with values `IstioIngressGatewayModeExternal`, `IstioIngressGatewayModeInternal` +- New enum type `ServiceMeshMode` with values `ServiceMeshModeDisabled`, `ServiceMeshModeIstio` +- New function `*ManagedClustersClient.GetMeshRevisionProfile(context.Context, string, string, *ManagedClustersClientGetMeshRevisionProfileOptions) (ManagedClustersClientGetMeshRevisionProfileResponse, error)` +- New function `*ManagedClustersClient.GetMeshUpgradeProfile(context.Context, string, string, string, *ManagedClustersClientGetMeshUpgradeProfileOptions) (ManagedClustersClientGetMeshUpgradeProfileResponse, error)` +- New function `*ManagedClustersClient.NewListMeshRevisionProfilesPager(string, *ManagedClustersClientListMeshRevisionProfilesOptions) *runtime.Pager[ManagedClustersClientListMeshRevisionProfilesResponse]` +- New function `*ManagedClustersClient.NewListMeshUpgradeProfilesPager(string, string, *ManagedClustersClientListMeshUpgradeProfilesOptions) *runtime.Pager[ManagedClustersClientListMeshUpgradeProfilesResponse]` +- New struct `CompatibleVersions` +- New struct `IstioCertificateAuthority` +- New struct `IstioComponents` +- New struct `IstioEgressGateway` +- New struct `IstioIngressGateway` +- New struct `IstioPluginCertificateAuthority` +- New struct `IstioServiceMesh` +- New struct `MeshRevision` +- New struct `MeshRevisionProfile` +- New struct `MeshRevisionProfileList` +- New struct `MeshRevisionProfileProperties` +- New struct `MeshUpgradeProfile` +- New struct `MeshUpgradeProfileList` +- New struct `MeshUpgradeProfileProperties` +- New struct `ServiceMeshProfile` +- New field `ResourceUID`, `ServiceMeshProfile` in struct `ManagedClusterProperties` + + +## 4.4.0-beta.2 (2023-10-09) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + +## 4.4.0-beta.1 (2023-09-22) +### Features Added + +- New value `NodeOSUpgradeChannelSecurityPatch` added to enum type `NodeOSUpgradeChannel` +- New value `OSSKUMariner` added to enum type `OSSKU` +- New value `PublicNetworkAccessSecuredByPerimeter` added to enum type `PublicNetworkAccess` +- New value `SnapshotTypeManagedCluster` added to enum type `SnapshotType` +- New value `WorkloadRuntimeKataMshvVMIsolation` added to enum type `WorkloadRuntime` +- New enum type `AgentPoolSSHAccess` with values `AgentPoolSSHAccessDisabled`, `AgentPoolSSHAccessLocalUser` +- New enum type `BackendPoolType` with values `BackendPoolTypeNodeIP`, `BackendPoolTypeNodeIPConfiguration` +- New enum type `GuardrailsSupport` with values `GuardrailsSupportPreview`, `GuardrailsSupportStable` +- New enum type `IpvsScheduler` with values `IpvsSchedulerLeastConnection`, `IpvsSchedulerRoundRobin` +- New enum type `IstioIngressGatewayMode` with values `IstioIngressGatewayModeExternal`, `IstioIngressGatewayModeInternal` +- New enum type `Level` with values `LevelEnforcement`, `LevelOff`, `LevelWarning` +- New enum type `Mode` with values `ModeIPTABLES`, `ModeIPVS` +- New enum type `Protocol` with values `ProtocolTCP`, `ProtocolUDP` +- New enum type `RestrictionLevel` with values `RestrictionLevelReadOnly`, `RestrictionLevelUnrestricted` +- New enum type `ServiceMeshMode` with values `ServiceMeshModeDisabled`, `ServiceMeshModeIstio` +- New enum type `TrustedAccessRoleBindingProvisioningState` with values `TrustedAccessRoleBindingProvisioningStateCanceled`, `TrustedAccessRoleBindingProvisioningStateDeleting`, `TrustedAccessRoleBindingProvisioningStateFailed`, `TrustedAccessRoleBindingProvisioningStateSucceeded`, `TrustedAccessRoleBindingProvisioningStateUpdating` +- New function `*ClientFactory.NewMachinesClient() *MachinesClient` +- New function `*ClientFactory.NewManagedClusterSnapshotsClient() *ManagedClusterSnapshotsClient` +- New function `*ClientFactory.NewTrustedAccessRoleBindingsClient() *TrustedAccessRoleBindingsClient` +- New function `*ClientFactory.NewTrustedAccessRolesClient() *TrustedAccessRolesClient` +- New function `NewMachinesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*MachinesClient, error)` +- New function `*MachinesClient.Get(context.Context, string, string, string, string, *MachinesClientGetOptions) (MachinesClientGetResponse, error)` +- New function `*MachinesClient.NewListPager(string, string, string, *MachinesClientListOptions) *runtime.Pager[MachinesClientListResponse]` +- New function `NewManagedClusterSnapshotsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagedClusterSnapshotsClient, error)` +- New function `*ManagedClusterSnapshotsClient.CreateOrUpdate(context.Context, string, string, ManagedClusterSnapshot, *ManagedClusterSnapshotsClientCreateOrUpdateOptions) (ManagedClusterSnapshotsClientCreateOrUpdateResponse, error)` +- New function `*ManagedClusterSnapshotsClient.Delete(context.Context, string, string, *ManagedClusterSnapshotsClientDeleteOptions) (ManagedClusterSnapshotsClientDeleteResponse, error)` +- New function `*ManagedClusterSnapshotsClient.Get(context.Context, string, string, *ManagedClusterSnapshotsClientGetOptions) (ManagedClusterSnapshotsClientGetResponse, error)` +- New function `*ManagedClusterSnapshotsClient.NewListByResourceGroupPager(string, *ManagedClusterSnapshotsClientListByResourceGroupOptions) *runtime.Pager[ManagedClusterSnapshotsClientListByResourceGroupResponse]` +- New function `*ManagedClusterSnapshotsClient.NewListPager(*ManagedClusterSnapshotsClientListOptions) *runtime.Pager[ManagedClusterSnapshotsClientListResponse]` +- New function `*ManagedClusterSnapshotsClient.UpdateTags(context.Context, string, string, TagsObject, *ManagedClusterSnapshotsClientUpdateTagsOptions) (ManagedClusterSnapshotsClientUpdateTagsResponse, error)` +- New function `*ManagedClustersClient.GetGuardrailsVersions(context.Context, string, string, *ManagedClustersClientGetGuardrailsVersionsOptions) (ManagedClustersClientGetGuardrailsVersionsResponse, error)` +- New function `*ManagedClustersClient.GetMeshRevisionProfile(context.Context, string, string, *ManagedClustersClientGetMeshRevisionProfileOptions) (ManagedClustersClientGetMeshRevisionProfileResponse, error)` +- New function `*ManagedClustersClient.GetMeshUpgradeProfile(context.Context, string, string, string, *ManagedClustersClientGetMeshUpgradeProfileOptions) (ManagedClustersClientGetMeshUpgradeProfileResponse, error)` +- New function `*ManagedClustersClient.NewListGuardrailsVersionsPager(string, *ManagedClustersClientListGuardrailsVersionsOptions) *runtime.Pager[ManagedClustersClientListGuardrailsVersionsResponse]` +- New function `*ManagedClustersClient.NewListMeshRevisionProfilesPager(string, *ManagedClustersClientListMeshRevisionProfilesOptions) *runtime.Pager[ManagedClustersClientListMeshRevisionProfilesResponse]` +- New function `*ManagedClustersClient.NewListMeshUpgradeProfilesPager(string, string, *ManagedClustersClientListMeshUpgradeProfilesOptions) *runtime.Pager[ManagedClustersClientListMeshUpgradeProfilesResponse]` +- New function `NewTrustedAccessRoleBindingsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*TrustedAccessRoleBindingsClient, error)` +- New function `*TrustedAccessRoleBindingsClient.CreateOrUpdate(context.Context, string, string, string, TrustedAccessRoleBinding, *TrustedAccessRoleBindingsClientCreateOrUpdateOptions) (TrustedAccessRoleBindingsClientCreateOrUpdateResponse, error)` +- New function `*TrustedAccessRoleBindingsClient.Delete(context.Context, string, string, string, *TrustedAccessRoleBindingsClientDeleteOptions) (TrustedAccessRoleBindingsClientDeleteResponse, error)` +- New function `*TrustedAccessRoleBindingsClient.Get(context.Context, string, string, string, *TrustedAccessRoleBindingsClientGetOptions) (TrustedAccessRoleBindingsClientGetResponse, error)` +- New function `*TrustedAccessRoleBindingsClient.NewListPager(string, string, *TrustedAccessRoleBindingsClientListOptions) *runtime.Pager[TrustedAccessRoleBindingsClientListResponse]` +- New function `NewTrustedAccessRolesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*TrustedAccessRolesClient, error)` +- New function `*TrustedAccessRolesClient.NewListPager(string, *TrustedAccessRolesClientListOptions) *runtime.Pager[TrustedAccessRolesClientListResponse]` +- New struct `AgentPoolNetworkProfile` +- New struct `AgentPoolSecurityProfile` +- New struct `AgentPoolWindowsProfile` +- New struct `CompatibleVersions` +- New struct `GuardrailsAvailableVersion` +- New struct `GuardrailsAvailableVersionsList` +- New struct `GuardrailsAvailableVersionsProperties` +- New struct `GuardrailsProfile` +- New struct `IPTag` +- New struct `IstioCertificateAuthority` +- New struct `IstioComponents` +- New struct `IstioIngressGateway` +- New struct `IstioPluginCertificateAuthority` +- New struct `IstioServiceMesh` +- New struct `Machine` +- New struct `MachineIPAddress` +- New struct `MachineListResult` +- New struct `MachineNetworkProperties` +- New struct `MachineProperties` +- New struct `ManagedClusterAzureMonitorProfileAppMonitoring` +- New struct `ManagedClusterAzureMonitorProfileAppMonitoringOpenTelemetryMetrics` +- New struct `ManagedClusterAzureMonitorProfileContainerInsights` +- New struct `ManagedClusterAzureMonitorProfileLogs` +- New struct `ManagedClusterAzureMonitorProfileWindowsHostLogs` +- New struct `ManagedClusterCostAnalysis` +- New struct `ManagedClusterIngressProfile` +- New struct `ManagedClusterIngressProfileWebAppRouting` +- New struct `ManagedClusterMetricsProfile` +- New struct `ManagedClusterNodeResourceGroupProfile` +- New struct `ManagedClusterPropertiesForSnapshot` +- New struct `ManagedClusterSecurityProfileImageIntegrity` +- New struct `ManagedClusterSecurityProfileNodeRestriction` +- New struct `ManagedClusterSnapshot` +- New struct `ManagedClusterSnapshotListResult` +- New struct `ManagedClusterSnapshotProperties` +- New struct `MeshRevision` +- New struct `MeshRevisionProfile` +- New struct `MeshRevisionProfileList` +- New struct `MeshRevisionProfileProperties` +- New struct `MeshUpgradeProfile` +- New struct `MeshUpgradeProfileList` +- New struct `MeshUpgradeProfileProperties` +- New struct `NetworkMonitoring` +- New struct `NetworkProfileForSnapshot` +- New struct `NetworkProfileKubeProxyConfig` +- New struct `NetworkProfileKubeProxyConfigIpvsConfig` +- New struct `PortRange` +- New struct `ServiceMeshProfile` +- New struct `TrustedAccessRole` +- New struct `TrustedAccessRoleBinding` +- New struct `TrustedAccessRoleBindingListResult` +- New struct `TrustedAccessRoleBindingProperties` +- New struct `TrustedAccessRoleListResult` +- New struct `TrustedAccessRoleRule` +- New field `IgnorePodDisruptionBudget` in struct `AgentPoolsClientBeginDeleteOptions` +- New field `EnableVnetIntegration`, `SubnetID` in struct `ManagedClusterAPIServerAccessProfile` +- New field `CapacityReservationGroupID`, `EnableCustomCATrust`, `MessageOfTheDay`, `NetworkProfile`, `SecurityProfile`, `WindowsProfile` in struct `ManagedClusterAgentPoolProfile` +- New field `CapacityReservationGroupID`, `EnableCustomCATrust`, `MessageOfTheDay`, `NetworkProfile`, `SecurityProfile`, `WindowsProfile` in struct `ManagedClusterAgentPoolProfileProperties` +- New field `Logs` in struct `ManagedClusterAzureMonitorProfile` +- New field `AppMonitoringOpenTelemetryMetrics` in struct `ManagedClusterAzureMonitorProfileMetrics` +- New field `EffectiveNoProxy` in struct `ManagedClusterHTTPProxyConfig` +- New field `BackendPoolType` in struct `ManagedClusterLoadBalancerProfile` +- New field `CreationData`, `EnableNamespaceResources`, `GuardrailsProfile`, `IngressProfile`, `MetricsProfile`, `NodeResourceGroupProfile`, `ResourceUID`, `ServiceMeshProfile` in struct `ManagedClusterProperties` +- New field `CustomCATrustCertificates`, `ImageIntegrity`, `NodeRestriction` in struct `ManagedClusterSecurityProfile` +- New field `Version` in struct `ManagedClusterStorageProfileDiskCSIDriver` +- New field `IgnorePodDisruptionBudget` in struct `ManagedClustersClientBeginDeleteOptions` +- New field `KubeProxyConfig`, `Monitoring` in struct `NetworkProfile` + + ## 4.3.0 (2023-08-25) ### Features Added diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go index 623e6fabcb..e265f4a5a3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/agentpools_client.go @@ -48,7 +48,7 @@ func NewAgentPoolsClient(subscriptionID string, credential azcore.TokenCredentia // before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -74,7 +74,7 @@ func (client *AgentPoolsClient) BeginAbortLatestOperation(ctx context.Context, r // before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *AgentPoolsClient) abortLatestOperation(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, options *AgentPoolsClientBeginAbortLatestOperationOptions) (*http.Response, error) { var err error req, err := client.abortLatestOperationCreateRequest(ctx, resourceGroupName, resourceName, agentPoolName, options) @@ -116,7 +116,7 @@ func (client *AgentPoolsClient) abortLatestOperationCreateRequest(ctx context.Co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -125,7 +125,7 @@ func (client *AgentPoolsClient) abortLatestOperationCreateRequest(ctx context.Co // BeginCreateOrUpdate - Creates or updates an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -148,7 +148,7 @@ func (client *AgentPoolsClient) BeginCreateOrUpdate(ctx context.Context, resourc // CreateOrUpdate - Creates or updates an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *AgentPoolsClient) createOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, parameters AgentPool, options *AgentPoolsClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, resourceName, agentPoolName, parameters, options) @@ -190,7 +190,7 @@ func (client *AgentPoolsClient) createOrUpdateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -202,7 +202,7 @@ func (client *AgentPoolsClient) createOrUpdateCreateRequest(ctx context.Context, // BeginDelete - Deletes an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -223,7 +223,7 @@ func (client *AgentPoolsClient) BeginDelete(ctx context.Context, resourceGroupNa // Delete - Deletes an agent pool in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *AgentPoolsClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*http.Response, error) { var err error req, err := client.deleteCreateRequest(ctx, resourceGroupName, resourceName, agentPoolName, options) @@ -265,7 +265,7 @@ func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourc return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -274,7 +274,7 @@ func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourc // Get - Gets the specified managed cluster agent pool. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -321,7 +321,7 @@ func (client *AgentPoolsClient) getCreateRequest(ctx context.Context, resourceGr return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -340,7 +340,7 @@ func (client *AgentPoolsClient) getHandleResponse(resp *http.Response) (AgentPoo // for more details about the version lifecycle. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - AgentPoolsClientGetAvailableAgentPoolVersionsOptions contains the optional parameters for the AgentPoolsClient.GetAvailableAgentPoolVersions @@ -383,7 +383,7 @@ func (client *AgentPoolsClient) getAvailableAgentPoolVersionsCreateRequest(ctx c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -401,7 +401,7 @@ func (client *AgentPoolsClient) getAvailableAgentPoolVersionsHandleResponse(resp // GetUpgradeProfile - Gets the upgrade profile for an agent pool. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -449,7 +449,7 @@ func (client *AgentPoolsClient) getUpgradeProfileCreateRequest(ctx context.Conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -466,7 +466,7 @@ func (client *AgentPoolsClient) getUpgradeProfileHandleResponse(resp *http.Respo // NewListPager - Gets a list of agent pools in the specified managed cluster. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - AgentPoolsClientListOptions contains the optional parameters for the AgentPoolsClient.NewListPager method. @@ -518,7 +518,7 @@ func (client *AgentPoolsClient) listCreateRequest(ctx context.Context, resourceG return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -538,7 +538,7 @@ func (client *AgentPoolsClient) listHandleResponse(resp *http.Response) (AgentPo // versions, see: https://docs.microsoft.com/azure/aks/node-image-upgrade // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - agentPoolName - The name of the agent pool. @@ -564,7 +564,7 @@ func (client *AgentPoolsClient) BeginUpgradeNodeImageVersion(ctx context.Context // versions, see: https://docs.microsoft.com/azure/aks/node-image-upgrade // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *AgentPoolsClient) upgradeNodeImageVersion(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, options *AgentPoolsClientBeginUpgradeNodeImageVersionOptions) (*http.Response, error) { var err error req, err := client.upgradeNodeImageVersionCreateRequest(ctx, resourceGroupName, resourceName, agentPoolName, options) @@ -606,7 +606,7 @@ func (client *AgentPoolsClient) upgradeNodeImageVersionCreateRequest(ctx context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json index f2be3ff2e6..a3f2bec74f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "go", "TagPrefix": "go/resourcemanager/containerservice/armcontainerservice", - "Tag": "go/resourcemanager/containerservice/armcontainerservice_7b6bc13370" + "Tag": "go/resourcemanager/containerservice/armcontainerservice_97daf8680c" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md index 74b4e13962..de86e99b68 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/autorest.md @@ -5,9 +5,9 @@ ``` yaml azure-arm: true require: -- https://github.com/Azure/azure-rest-api-specs/blob/1d2b8c05b55be5dd98ce94c835d7e96ee1ea7f5d/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/1d2b8c05b55be5dd98ce94c835d7e96ee1ea7f5d/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.go.md +- https://github.com/Azure/azure-rest-api-specs/blob/0a25ea9680cf080b7d34e8c5f35f564425c6b1f7/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/0a25ea9680cf080b7d34e8c5f35f564425c6b1f7/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 4.3.0 -tag: package-2023-07 +module-version: 4.4.0 +tag: package-2023-08 ``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go index 36e47bef0d..68aefcae74 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/constants.go @@ -10,7 +10,7 @@ package armcontainerservice const ( moduleName = "armcontainerservice" - moduleVersion = "v4.3.0" + moduleVersion = "v4.4.0" ) // AgentPoolMode - A cluster must have at least one 'System' Agent Pool at all times. For additional information on agent @@ -209,6 +209,24 @@ func PossibleIPFamilyValues() []IPFamily { } } +// IstioIngressGatewayMode - Mode of an ingress gateway. +type IstioIngressGatewayMode string + +const ( + // IstioIngressGatewayModeExternal - The ingress gateway is assigned a public IP address and is publicly accessible. + IstioIngressGatewayModeExternal IstioIngressGatewayMode = "External" + // IstioIngressGatewayModeInternal - The ingress gateway is assigned an internal IP address and cannot is accessed publicly. + IstioIngressGatewayModeInternal IstioIngressGatewayMode = "Internal" +) + +// PossibleIstioIngressGatewayModeValues returns the possible values for the IstioIngressGatewayMode const type. +func PossibleIstioIngressGatewayModeValues() []IstioIngressGatewayMode { + return []IstioIngressGatewayMode{ + IstioIngressGatewayModeExternal, + IstioIngressGatewayModeInternal, + } +} + // KeyVaultNetworkAccessTypes - Network access of key vault. The possible values are Public and Private. Public means the // key vault allows public access from all networks. Private means the key vault disables public access and // enables private link. The default value is Public. @@ -724,6 +742,24 @@ func PossibleScaleSetPriorityValues() []ScaleSetPriority { } } +// ServiceMeshMode - Mode of the service mesh. +type ServiceMeshMode string + +const ( + // ServiceMeshModeDisabled - Mesh is disabled. + ServiceMeshModeDisabled ServiceMeshMode = "Disabled" + // ServiceMeshModeIstio - Istio deployed as an AKS addon. + ServiceMeshModeIstio ServiceMeshMode = "Istio" +) + +// PossibleServiceMeshModeValues returns the possible values for the ServiceMeshMode const type. +func PossibleServiceMeshModeValues() []ServiceMeshMode { + return []ServiceMeshMode{ + ServiceMeshModeDisabled, + ServiceMeshModeIstio, + } +} + // SnapshotType - The type of a snapshot. The default is NodePool. type SnapshotType string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go index 8e14b59d73..2b177987c1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/maintenanceconfigurations_client.go @@ -46,7 +46,7 @@ func NewMaintenanceConfigurationsClient(subscriptionID string, credential azcore // CreateOrUpdate - Creates or updates a maintenance configuration in the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - configName - The name of the maintenance configuration. @@ -95,7 +95,7 @@ func (client *MaintenanceConfigurationsClient) createOrUpdateCreateRequest(ctx c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -116,7 +116,7 @@ func (client *MaintenanceConfigurationsClient) createOrUpdateHandleResponse(resp // Delete - Deletes a maintenance configuration. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - configName - The name of the maintenance configuration. @@ -163,7 +163,7 @@ func (client *MaintenanceConfigurationsClient) deleteCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -172,7 +172,7 @@ func (client *MaintenanceConfigurationsClient) deleteCreateRequest(ctx context.C // Get - Gets the specified maintenance configuration of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - configName - The name of the maintenance configuration. @@ -220,7 +220,7 @@ func (client *MaintenanceConfigurationsClient) getCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -237,7 +237,7 @@ func (client *MaintenanceConfigurationsClient) getHandleResponse(resp *http.Resp // NewListByManagedClusterPager - Gets a list of maintenance configurations in the specified managed cluster. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - MaintenanceConfigurationsClientListByManagedClusterOptions contains the optional parameters for the MaintenanceConfigurationsClient.NewListByManagedClusterPager @@ -290,7 +290,7 @@ func (client *MaintenanceConfigurationsClient) listByManagedClusterCreateRequest return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go index bf9f59c7ae..beb51d9bb0 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/managedclusters_client.go @@ -48,7 +48,7 @@ func NewManagedClustersClient(subscriptionID string, credential azcore.TokenCred // completes before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginAbortLatestOperationOptions contains the optional parameters for the ManagedClustersClient.BeginAbortLatestOperation @@ -73,7 +73,7 @@ func (client *ManagedClustersClient) BeginAbortLatestOperation(ctx context.Conte // completes before cancellation can take place, a 409 error code is returned. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) abortLatestOperation(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginAbortLatestOperationOptions) (*http.Response, error) { var err error req, err := client.abortLatestOperationCreateRequest(ctx, resourceGroupName, resourceName, options) @@ -111,7 +111,7 @@ func (client *ManagedClustersClient) abortLatestOperationCreateRequest(ctx conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -120,7 +120,7 @@ func (client *ManagedClustersClient) abortLatestOperationCreateRequest(ctx conte // BeginCreateOrUpdate - Creates or updates a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The managed cluster to create or update. @@ -142,7 +142,7 @@ func (client *ManagedClustersClient) BeginCreateOrUpdate(ctx context.Context, re // CreateOrUpdate - Creates or updates a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, parameters ManagedCluster, options *ManagedClustersClientBeginCreateOrUpdateOptions) (*http.Response, error) { var err error req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, resourceName, parameters, options) @@ -180,7 +180,7 @@ func (client *ManagedClustersClient) createOrUpdateCreateRequest(ctx context.Con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -192,7 +192,7 @@ func (client *ManagedClustersClient) createOrUpdateCreateRequest(ctx context.Con // BeginDelete - Deletes a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginDeleteOptions contains the optional parameters for the ManagedClustersClient.BeginDelete @@ -213,7 +213,7 @@ func (client *ManagedClustersClient) BeginDelete(ctx context.Context, resourceGr // Delete - Deletes a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginDeleteOptions) (*http.Response, error) { var err error req, err := client.deleteCreateRequest(ctx, resourceGroupName, resourceName, options) @@ -251,7 +251,7 @@ func (client *ManagedClustersClient) deleteCreateRequest(ctx context.Context, re return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -260,7 +260,7 @@ func (client *ManagedClustersClient) deleteCreateRequest(ctx context.Context, re // Get - Gets a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientGetOptions contains the optional parameters for the ManagedClustersClient.Get method. @@ -302,7 +302,7 @@ func (client *ManagedClustersClient) getCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -322,7 +322,7 @@ func (client *ManagedClustersClient) getHandleResponse(resp *http.Response) (Man // [https://docs.microsoft.com/rest/api/aks/managedclusters/listclusteradmincredentials] . // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - roleName - The name of the role for managed cluster accessProfile resource. @@ -370,7 +370,7 @@ func (client *ManagedClustersClient) getAccessProfileCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -388,7 +388,7 @@ func (client *ManagedClustersClient) getAccessProfileHandleResponse(resp *http.R // GetCommandResult - Gets the results of a command which has been run on the Managed Cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - commandID - Id of the command. @@ -436,7 +436,7 @@ func (client *ManagedClustersClient) getCommandResultCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -454,10 +454,138 @@ func (client *ManagedClustersClient) getCommandResultHandleResponse(resp *http.R return result, nil } +// GetMeshRevisionProfile - Contains extra metadata on the revision, including supported revisions, cluster compatibility +// and available upgrades +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-08-01 +// - location - The name of Azure region. +// - mode - The mode of the mesh. +// - options - ManagedClustersClientGetMeshRevisionProfileOptions contains the optional parameters for the ManagedClustersClient.GetMeshRevisionProfile +// method. +func (client *ManagedClustersClient) GetMeshRevisionProfile(ctx context.Context, location string, mode string, options *ManagedClustersClientGetMeshRevisionProfileOptions) (ManagedClustersClientGetMeshRevisionProfileResponse, error) { + var err error + req, err := client.getMeshRevisionProfileCreateRequest(ctx, location, mode, options) + if err != nil { + return ManagedClustersClientGetMeshRevisionProfileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedClustersClientGetMeshRevisionProfileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedClustersClientGetMeshRevisionProfileResponse{}, err + } + resp, err := client.getMeshRevisionProfileHandleResponse(httpResp) + return resp, err +} + +// getMeshRevisionProfileCreateRequest creates the GetMeshRevisionProfile request. +func (client *ManagedClustersClient) getMeshRevisionProfileCreateRequest(ctx context.Context, location string, mode string, options *ManagedClustersClientGetMeshRevisionProfileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/locations/{location}/meshRevisionProfiles/{mode}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if mode == "" { + return nil, errors.New("parameter mode cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mode}", url.PathEscape(mode)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getMeshRevisionProfileHandleResponse handles the GetMeshRevisionProfile response. +func (client *ManagedClustersClient) getMeshRevisionProfileHandleResponse(resp *http.Response) (ManagedClustersClientGetMeshRevisionProfileResponse, error) { + result := ManagedClustersClientGetMeshRevisionProfileResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MeshRevisionProfile); err != nil { + return ManagedClustersClientGetMeshRevisionProfileResponse{}, err + } + return result, nil +} + +// GetMeshUpgradeProfile - Gets available upgrades for a service mesh in a cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-08-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceName - The name of the managed cluster resource. +// - mode - The mode of the mesh. +// - options - ManagedClustersClientGetMeshUpgradeProfileOptions contains the optional parameters for the ManagedClustersClient.GetMeshUpgradeProfile +// method. +func (client *ManagedClustersClient) GetMeshUpgradeProfile(ctx context.Context, resourceGroupName string, resourceName string, mode string, options *ManagedClustersClientGetMeshUpgradeProfileOptions) (ManagedClustersClientGetMeshUpgradeProfileResponse, error) { + var err error + req, err := client.getMeshUpgradeProfileCreateRequest(ctx, resourceGroupName, resourceName, mode, options) + if err != nil { + return ManagedClustersClientGetMeshUpgradeProfileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedClustersClientGetMeshUpgradeProfileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedClustersClientGetMeshUpgradeProfileResponse{}, err + } + resp, err := client.getMeshUpgradeProfileHandleResponse(httpResp) + return resp, err +} + +// getMeshUpgradeProfileCreateRequest creates the GetMeshUpgradeProfile request. +func (client *ManagedClustersClient) getMeshUpgradeProfileCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, mode string, options *ManagedClustersClientGetMeshUpgradeProfileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/meshUpgradeProfiles/{mode}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceName == "" { + return nil, errors.New("parameter resourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName)) + if mode == "" { + return nil, errors.New("parameter mode cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mode}", url.PathEscape(mode)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getMeshUpgradeProfileHandleResponse handles the GetMeshUpgradeProfile response. +func (client *ManagedClustersClient) getMeshUpgradeProfileHandleResponse(resp *http.Response) (ManagedClustersClientGetMeshUpgradeProfileResponse, error) { + result := ManagedClustersClientGetMeshUpgradeProfileResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MeshUpgradeProfile); err != nil { + return ManagedClustersClientGetMeshUpgradeProfileResponse{}, err + } + return result, nil +} + // GetOSOptions - Gets supported OS options in the specified subscription. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - location - The name of Azure region. // - options - ManagedClustersClientGetOSOptionsOptions contains the optional parameters for the ManagedClustersClient.GetOSOptions // method. @@ -495,7 +623,7 @@ func (client *ManagedClustersClient) getOSOptionsCreateRequest(ctx context.Conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") if options != nil && options.ResourceType != nil { reqQP.Set("resource-type", *options.ResourceType) } @@ -516,7 +644,7 @@ func (client *ManagedClustersClient) getOSOptionsHandleResponse(resp *http.Respo // GetUpgradeProfile - Gets the upgrade profile of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientGetUpgradeProfileOptions contains the optional parameters for the ManagedClustersClient.GetUpgradeProfile @@ -559,7 +687,7 @@ func (client *ManagedClustersClient) getUpgradeProfileCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -576,7 +704,7 @@ func (client *ManagedClustersClient) getUpgradeProfileHandleResponse(resp *http. // NewListPager - Gets a list of managed clusters in the specified subscription. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - options - ManagedClustersClientListOptions contains the optional parameters for the ManagedClustersClient.NewListPager // method. func (client *ManagedClustersClient) NewListPager(options *ManagedClustersClientListOptions) *runtime.Pager[ManagedClustersClientListResponse] { @@ -619,7 +747,7 @@ func (client *ManagedClustersClient) listCreateRequest(ctx context.Context, opti return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -636,7 +764,7 @@ func (client *ManagedClustersClient) listHandleResponse(resp *http.Response) (Ma // NewListByResourceGroupPager - Lists managed clusters in the specified subscription and resource group. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - ManagedClustersClientListByResourceGroupOptions contains the optional parameters for the ManagedClustersClient.NewListByResourceGroupPager // method. @@ -684,7 +812,7 @@ func (client *ManagedClustersClient) listByResourceGroupCreateRequest(ctx contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -702,7 +830,7 @@ func (client *ManagedClustersClient) listByResourceGroupHandleResponse(resp *htt // ListClusterAdminCredentials - Lists the admin credentials of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListClusterAdminCredentialsOptions contains the optional parameters for the ManagedClustersClient.ListClusterAdminCredentials @@ -745,7 +873,7 @@ func (client *ManagedClustersClient) listClusterAdminCredentialsCreateRequest(ct return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") if options != nil && options.ServerFqdn != nil { reqQP.Set("server-fqdn", *options.ServerFqdn) } @@ -766,7 +894,7 @@ func (client *ManagedClustersClient) listClusterAdminCredentialsHandleResponse(r // ListClusterMonitoringUserCredentials - Lists the cluster monitoring user credentials of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListClusterMonitoringUserCredentialsOptions contains the optional parameters for the ManagedClustersClient.ListClusterMonitoringUserCredentials @@ -809,7 +937,7 @@ func (client *ManagedClustersClient) listClusterMonitoringUserCredentialsCreateR return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") if options != nil && options.ServerFqdn != nil { reqQP.Set("server-fqdn", *options.ServerFqdn) } @@ -830,7 +958,7 @@ func (client *ManagedClustersClient) listClusterMonitoringUserCredentialsHandleR // ListClusterUserCredentials - Lists the user credentials of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListClusterUserCredentialsOptions contains the optional parameters for the ManagedClustersClient.ListClusterUserCredentials @@ -873,7 +1001,7 @@ func (client *ManagedClustersClient) listClusterUserCredentialsCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") if options != nil && options.ServerFqdn != nil { reqQP.Set("server-fqdn", *options.ServerFqdn) } @@ -898,7 +1026,7 @@ func (client *ManagedClustersClient) listClusterUserCredentialsHandleResponse(re // upgrades, and details on preview status of the version // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - location - The name of Azure region. // - options - ManagedClustersClientListKubernetesVersionsOptions contains the optional parameters for the ManagedClustersClient.ListKubernetesVersions // method. @@ -936,7 +1064,7 @@ func (client *ManagedClustersClient) listKubernetesVersionsCreateRequest(ctx con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -951,10 +1079,146 @@ func (client *ManagedClustersClient) listKubernetesVersionsHandleResponse(resp * return result, nil } +// NewListMeshRevisionProfilesPager - Contains extra metadata on each revision, including supported revisions, cluster compatibility +// and available upgrades +// +// Generated from API version 2023-08-01 +// - location - The name of Azure region. +// - options - ManagedClustersClientListMeshRevisionProfilesOptions contains the optional parameters for the ManagedClustersClient.NewListMeshRevisionProfilesPager +// method. +func (client *ManagedClustersClient) NewListMeshRevisionProfilesPager(location string, options *ManagedClustersClientListMeshRevisionProfilesOptions) *runtime.Pager[ManagedClustersClientListMeshRevisionProfilesResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedClustersClientListMeshRevisionProfilesResponse]{ + More: func(page ManagedClustersClientListMeshRevisionProfilesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedClustersClientListMeshRevisionProfilesResponse) (ManagedClustersClientListMeshRevisionProfilesResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listMeshRevisionProfilesCreateRequest(ctx, location, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedClustersClientListMeshRevisionProfilesResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedClustersClientListMeshRevisionProfilesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedClustersClientListMeshRevisionProfilesResponse{}, runtime.NewResponseError(resp) + } + return client.listMeshRevisionProfilesHandleResponse(resp) + }, + }) +} + +// listMeshRevisionProfilesCreateRequest creates the ListMeshRevisionProfiles request. +func (client *ManagedClustersClient) listMeshRevisionProfilesCreateRequest(ctx context.Context, location string, options *ManagedClustersClientListMeshRevisionProfilesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/locations/{location}/meshRevisionProfiles" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listMeshRevisionProfilesHandleResponse handles the ListMeshRevisionProfiles response. +func (client *ManagedClustersClient) listMeshRevisionProfilesHandleResponse(resp *http.Response) (ManagedClustersClientListMeshRevisionProfilesResponse, error) { + result := ManagedClustersClientListMeshRevisionProfilesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MeshRevisionProfileList); err != nil { + return ManagedClustersClientListMeshRevisionProfilesResponse{}, err + } + return result, nil +} + +// NewListMeshUpgradeProfilesPager - Lists available upgrades for all service meshes in a specific cluster. +// +// Generated from API version 2023-08-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceName - The name of the managed cluster resource. +// - options - ManagedClustersClientListMeshUpgradeProfilesOptions contains the optional parameters for the ManagedClustersClient.NewListMeshUpgradeProfilesPager +// method. +func (client *ManagedClustersClient) NewListMeshUpgradeProfilesPager(resourceGroupName string, resourceName string, options *ManagedClustersClientListMeshUpgradeProfilesOptions) *runtime.Pager[ManagedClustersClientListMeshUpgradeProfilesResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedClustersClientListMeshUpgradeProfilesResponse]{ + More: func(page ManagedClustersClientListMeshUpgradeProfilesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedClustersClientListMeshUpgradeProfilesResponse) (ManagedClustersClientListMeshUpgradeProfilesResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listMeshUpgradeProfilesCreateRequest(ctx, resourceGroupName, resourceName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedClustersClientListMeshUpgradeProfilesResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedClustersClientListMeshUpgradeProfilesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedClustersClientListMeshUpgradeProfilesResponse{}, runtime.NewResponseError(resp) + } + return client.listMeshUpgradeProfilesHandleResponse(resp) + }, + }) +} + +// listMeshUpgradeProfilesCreateRequest creates the ListMeshUpgradeProfiles request. +func (client *ManagedClustersClient) listMeshUpgradeProfilesCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientListMeshUpgradeProfilesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/meshUpgradeProfiles" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceName == "" { + return nil, errors.New("parameter resourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listMeshUpgradeProfilesHandleResponse handles the ListMeshUpgradeProfiles response. +func (client *ManagedClustersClient) listMeshUpgradeProfilesHandleResponse(resp *http.Response) (ManagedClustersClientListMeshUpgradeProfilesResponse, error) { + result := ManagedClustersClientListMeshUpgradeProfilesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MeshUpgradeProfileList); err != nil { + return ManagedClustersClientListMeshUpgradeProfilesResponse{}, err + } + return result, nil +} + // NewListOutboundNetworkDependenciesEndpointsPager - Gets a list of egress endpoints (network endpoints of all outbound dependencies) // in the specified managed cluster. The operation returns properties of each egress endpoint. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientListOutboundNetworkDependenciesEndpointsOptions contains the optional parameters for the @@ -1007,7 +1271,7 @@ func (client *ManagedClustersClient) listOutboundNetworkDependenciesEndpointsCre return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1026,7 +1290,7 @@ func (client *ManagedClustersClient) listOutboundNetworkDependenciesEndpointsHan // [https://aka.ms/aks-managed-aad] to update your cluster with AKS-managed Azure AD. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The AAD profile to set on the Managed Cluster @@ -1051,7 +1315,7 @@ func (client *ManagedClustersClient) BeginResetAADProfile(ctx context.Context, r // to update your cluster with AKS-managed Azure AD. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) resetAADProfile(ctx context.Context, resourceGroupName string, resourceName string, parameters ManagedClusterAADProfile, options *ManagedClustersClientBeginResetAADProfileOptions) (*http.Response, error) { var err error req, err := client.resetAADProfileCreateRequest(ctx, resourceGroupName, resourceName, parameters, options) @@ -1089,7 +1353,7 @@ func (client *ManagedClustersClient) resetAADProfileCreateRequest(ctx context.Co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -1101,7 +1365,7 @@ func (client *ManagedClustersClient) resetAADProfileCreateRequest(ctx context.Co // BeginResetServicePrincipalProfile - This action cannot be performed on a cluster that is not using a service principal // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The service principal profile to set on the managed cluster. @@ -1125,7 +1389,7 @@ func (client *ManagedClustersClient) BeginResetServicePrincipalProfile(ctx conte // ResetServicePrincipalProfile - This action cannot be performed on a cluster that is not using a service principal // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) resetServicePrincipalProfile(ctx context.Context, resourceGroupName string, resourceName string, parameters ManagedClusterServicePrincipalProfile, options *ManagedClustersClientBeginResetServicePrincipalProfileOptions) (*http.Response, error) { var err error req, err := client.resetServicePrincipalProfileCreateRequest(ctx, resourceGroupName, resourceName, parameters, options) @@ -1163,7 +1427,7 @@ func (client *ManagedClustersClient) resetServicePrincipalProfileCreateRequest(c return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -1176,7 +1440,7 @@ func (client *ManagedClustersClient) resetServicePrincipalProfileCreateRequest(c // more details about rotating managed cluster certificates. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginRotateClusterCertificatesOptions contains the optional parameters for the ManagedClustersClient.BeginRotateClusterCertificates @@ -1200,7 +1464,7 @@ func (client *ManagedClustersClient) BeginRotateClusterCertificates(ctx context. // details about rotating managed cluster certificates. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) rotateClusterCertificates(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginRotateClusterCertificatesOptions) (*http.Response, error) { var err error req, err := client.rotateClusterCertificatesCreateRequest(ctx, resourceGroupName, resourceName, options) @@ -1238,7 +1502,7 @@ func (client *ManagedClustersClient) rotateClusterCertificatesCreateRequest(ctx return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1247,7 +1511,7 @@ func (client *ManagedClustersClient) rotateClusterCertificatesCreateRequest(ctx // BeginRotateServiceAccountSigningKeys - Rotates the service account signing keys of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginRotateServiceAccountSigningKeysOptions contains the optional parameters for the ManagedClustersClient.BeginRotateServiceAccountSigningKeys @@ -1270,7 +1534,7 @@ func (client *ManagedClustersClient) BeginRotateServiceAccountSigningKeys(ctx co // RotateServiceAccountSigningKeys - Rotates the service account signing keys of a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) rotateServiceAccountSigningKeys(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginRotateServiceAccountSigningKeysOptions) (*http.Response, error) { var err error req, err := client.rotateServiceAccountSigningKeysCreateRequest(ctx, resourceGroupName, resourceName, options) @@ -1308,7 +1572,7 @@ func (client *ManagedClustersClient) rotateServiceAccountSigningKeysCreateReques return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1319,7 +1583,7 @@ func (client *ManagedClustersClient) rotateServiceAccountSigningKeysCreateReques // [https://docs.microsoft.com/azure/aks/private-clusters#aks-run-command-preview]. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - requestPayload - The run command request @@ -1345,7 +1609,7 @@ func (client *ManagedClustersClient) BeginRunCommand(ctx context.Context, resour // [https://docs.microsoft.com/azure/aks/private-clusters#aks-run-command-preview]. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) runCommand(ctx context.Context, resourceGroupName string, resourceName string, requestPayload RunCommandRequest, options *ManagedClustersClientBeginRunCommandOptions) (*http.Response, error) { var err error req, err := client.runCommandCreateRequest(ctx, resourceGroupName, resourceName, requestPayload, options) @@ -1383,7 +1647,7 @@ func (client *ManagedClustersClient) runCommandCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, requestPayload); err != nil { @@ -1396,7 +1660,7 @@ func (client *ManagedClustersClient) runCommandCreateRequest(ctx context.Context // a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginStartOptions contains the optional parameters for the ManagedClustersClient.BeginStart @@ -1420,7 +1684,7 @@ func (client *ManagedClustersClient) BeginStart(ctx context.Context, resourceGro // a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) start(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginStartOptions) (*http.Response, error) { var err error req, err := client.startCreateRequest(ctx, resourceGroupName, resourceName, options) @@ -1458,7 +1722,7 @@ func (client *ManagedClustersClient) startCreateRequest(ctx context.Context, res return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1470,7 +1734,7 @@ func (client *ManagedClustersClient) startCreateRequest(ctx context.Context, res // for more details about stopping a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - ManagedClustersClientBeginStopOptions contains the optional parameters for the ManagedClustersClient.BeginStop @@ -1496,7 +1760,7 @@ func (client *ManagedClustersClient) BeginStop(ctx context.Context, resourceGrou // for more details about stopping a cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) stop(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientBeginStopOptions) (*http.Response, error) { var err error req, err := client.stopCreateRequest(ctx, resourceGroupName, resourceName, options) @@ -1534,7 +1798,7 @@ func (client *ManagedClustersClient) stopCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -1543,7 +1807,7 @@ func (client *ManagedClustersClient) stopCreateRequest(ctx context.Context, reso // BeginUpdateTags - Updates tags on a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - Parameters supplied to the Update Managed Cluster Tags operation. @@ -1565,7 +1829,7 @@ func (client *ManagedClustersClient) BeginUpdateTags(ctx context.Context, resour // UpdateTags - Updates tags on a managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *ManagedClustersClient) updateTags(ctx context.Context, resourceGroupName string, resourceName string, parameters TagsObject, options *ManagedClustersClientBeginUpdateTagsOptions) (*http.Response, error) { var err error req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, resourceName, parameters, options) @@ -1603,7 +1867,7 @@ func (client *ManagedClustersClient) updateTagsCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go index 4c7940a3be..e435a8643b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models.go @@ -182,6 +182,15 @@ type CommandResultProperties struct { StartedAt *time.Time } +// CompatibleVersions - Version information about a product/service that is compatible with a service mesh revision. +type CompatibleVersions struct { + // The product/service name. + Name *string + + // Product/service versions compatible with a service mesh add-on revision. + Versions []*string +} + // CreationData - Data used when creating a target resource from a source resource. type CreationData struct { // This is the ARM ID of the source object to be used to create the target object. @@ -266,6 +275,75 @@ type ExtendedLocation struct { Type *ExtendedLocationTypes } +// IstioCertificateAuthority - Istio Service Mesh Certificate Authority (CA) configuration. For now, we only support plugin +// certificates as described here https://aka.ms/asm-plugin-ca +type IstioCertificateAuthority struct { + // Plugin certificates information for Service Mesh. + Plugin *IstioPluginCertificateAuthority +} + +// IstioComponents - Istio components configuration. +type IstioComponents struct { + // Istio egress gateways. + EgressGateways []*IstioEgressGateway + + // Istio ingress gateways. + IngressGateways []*IstioIngressGateway +} + +// IstioEgressGateway - Istio egress gateway configuration. +type IstioEgressGateway struct { + // REQUIRED; Whether to enable the egress gateway. + Enabled *bool + + // NodeSelector for scheduling the egress gateway. + NodeSelector map[string]*string +} + +// IstioIngressGateway - Istio ingress gateway configuration. For now, we support up to one external ingress gateway named +// aks-istio-ingressgateway-external and one internal ingress gateway named +// aks-istio-ingressgateway-internal. +type IstioIngressGateway struct { + // REQUIRED; Whether to enable the ingress gateway. + Enabled *bool + + // REQUIRED; Mode of an ingress gateway. + Mode *IstioIngressGatewayMode +} + +// IstioPluginCertificateAuthority - Plugin certificates information for Service Mesh. +type IstioPluginCertificateAuthority struct { + // Certificate chain object name in Azure Key Vault. + CertChainObjectName *string + + // Intermediate certificate object name in Azure Key Vault. + CertObjectName *string + + // Intermediate certificate private key object name in Azure Key Vault. + KeyObjectName *string + + // The resource ID of the Key Vault. + KeyVaultID *string + + // Root certificate object name in Azure Key Vault. + RootCertObjectName *string +} + +// IstioServiceMesh - Istio service mesh configuration. +type IstioServiceMesh struct { + // Istio Service Mesh Certificate Authority (CA) configuration. For now, we only support plugin certificates as described + // here https://aka.ms/asm-plugin-ca + CertificateAuthority *IstioCertificateAuthority + + // Istio components configuration. + Components *IstioComponents + + // The list of revisions of the Istio control plane. When an upgrade is not in progress, this holds one value. When canary + // upgrade is in progress, this can only hold two consecutive values. For more + // information, see: https://learn.microsoft.com/en-us/azure/aks/istio-upgrade + Revisions []*string +} + // KubeletConfig - See AKS custom node configuration [https://docs.microsoft.com/azure/aks/custom-node-configuration] for // more details. type KubeletConfig struct { @@ -1233,6 +1311,9 @@ type ManagedClusterProperties struct { // Security profile for the managed cluster. SecurityProfile *ManagedClusterSecurityProfile + // Service mesh profile for a managed cluster. + ServiceMeshProfile *ServiceMeshProfile + // Information about a service principal identity for the cluster to use for manipulating Azure APIs. ServicePrincipalProfile *ManagedClusterServicePrincipalProfile @@ -1274,6 +1355,10 @@ type ManagedClusterProperties struct { // READ-ONLY; The current provisioning state. ProvisioningState *string + + // READ-ONLY; The resourceUID uniquely identifies ManagedClusters that reuse ARM ResourceIds (i.e: create, delete, create + // sequence) + ResourceUID *string } // ManagedClusterPropertiesAutoScalerProfile - Parameters to be applied to the cluster-autoscaler when enabled @@ -1534,6 +1619,89 @@ type ManagedServiceIdentityUserAssignedIdentitiesValue struct { PrincipalID *string } +// MeshRevision - Holds information on upgrades and compatibility for given major.minor mesh release. +type MeshRevision struct { + // List of items this revision of service mesh is compatible with, and their associated versions. + CompatibleWith []*CompatibleVersions + + // The revision of the mesh release. + Revision *string + + // List of revisions available for upgrade of a specific mesh revision + Upgrades []*string +} + +// MeshRevisionProfile - Mesh revision profile for a mesh. +type MeshRevisionProfile struct { + // Mesh revision profile properties for a mesh + Properties *MeshRevisionProfileProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MeshRevisionProfileList - Holds an array of MeshRevisionsProfiles +type MeshRevisionProfileList struct { + // Array of service mesh add-on revision profiles for all supported mesh modes. + Value []*MeshRevisionProfile + + // READ-ONLY; The URL to get the next set of mesh revision profile. + NextLink *string +} + +// MeshRevisionProfileProperties - Mesh revision profile properties for a mesh +type MeshRevisionProfileProperties struct { + MeshRevisions []*MeshRevision +} + +// MeshUpgradeProfile - Upgrade profile for given mesh. +type MeshUpgradeProfile struct { + // Mesh upgrade profile properties for a major.minor release. + Properties *MeshUpgradeProfileProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MeshUpgradeProfileList - Holds an array of MeshUpgradeProfiles +type MeshUpgradeProfileList struct { + // Array of supported service mesh add-on upgrade profiles. + Value []*MeshUpgradeProfile + + // READ-ONLY; The URL to get the next set of mesh upgrade profile. + NextLink *string +} + +// MeshUpgradeProfileProperties - Mesh upgrade profile properties for a major.minor release. +type MeshUpgradeProfileProperties struct { + // List of items this revision of service mesh is compatible with, and their associated versions. + CompatibleWith []*CompatibleVersions + + // The revision of the mesh release. + Revision *string + + // List of revisions available for upgrade of a specific mesh revision + Upgrades []*string +} + // NetworkProfile - Profile of network configuration. type NetworkProfile struct { // An IP address assigned to the Kubernetes DNS service. It must be within the Kubernetes service address range specified @@ -1819,6 +1987,15 @@ type Schedule struct { Weekly *WeeklySchedule } +// ServiceMeshProfile - Service mesh profile for a managed cluster. +type ServiceMeshProfile struct { + // REQUIRED; Mode of the service mesh. + Mode *ServiceMeshMode + + // Istio service mesh configuration. + Istio *IstioServiceMesh +} + // Snapshot - A node pool snapshot resource. type Snapshot struct { // REQUIRED; The geo-location where the resource lives diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go index 506fbd4564..b64908740e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/models_serde.go @@ -498,6 +498,37 @@ func (c *CommandResultProperties) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type CompatibleVersions. +func (c CompatibleVersions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "versions", c.Versions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CompatibleVersions. +func (c *CompatibleVersions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "versions": + err = unpopulate(val, "Versions", &c.Versions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type CreationData. func (c CreationData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -781,6 +812,204 @@ func (e *ExtendedLocation) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type IstioCertificateAuthority. +func (i IstioCertificateAuthority) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "plugin", i.Plugin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IstioCertificateAuthority. +func (i *IstioCertificateAuthority) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "plugin": + err = unpopulate(val, "Plugin", &i.Plugin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IstioComponents. +func (i IstioComponents) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "egressGateways", i.EgressGateways) + populate(objectMap, "ingressGateways", i.IngressGateways) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IstioComponents. +func (i *IstioComponents) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "egressGateways": + err = unpopulate(val, "EgressGateways", &i.EgressGateways) + delete(rawMsg, key) + case "ingressGateways": + err = unpopulate(val, "IngressGateways", &i.IngressGateways) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IstioEgressGateway. +func (i IstioEgressGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", i.Enabled) + populate(objectMap, "nodeSelector", i.NodeSelector) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IstioEgressGateway. +func (i *IstioEgressGateway) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &i.Enabled) + delete(rawMsg, key) + case "nodeSelector": + err = unpopulate(val, "NodeSelector", &i.NodeSelector) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IstioIngressGateway. +func (i IstioIngressGateway) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", i.Enabled) + populate(objectMap, "mode", i.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IstioIngressGateway. +func (i *IstioIngressGateway) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &i.Enabled) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &i.Mode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IstioPluginCertificateAuthority. +func (i IstioPluginCertificateAuthority) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certChainObjectName", i.CertChainObjectName) + populate(objectMap, "certObjectName", i.CertObjectName) + populate(objectMap, "keyObjectName", i.KeyObjectName) + populate(objectMap, "keyVaultId", i.KeyVaultID) + populate(objectMap, "rootCertObjectName", i.RootCertObjectName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IstioPluginCertificateAuthority. +func (i *IstioPluginCertificateAuthority) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certChainObjectName": + err = unpopulate(val, "CertChainObjectName", &i.CertChainObjectName) + delete(rawMsg, key) + case "certObjectName": + err = unpopulate(val, "CertObjectName", &i.CertObjectName) + delete(rawMsg, key) + case "keyObjectName": + err = unpopulate(val, "KeyObjectName", &i.KeyObjectName) + delete(rawMsg, key) + case "keyVaultId": + err = unpopulate(val, "KeyVaultID", &i.KeyVaultID) + delete(rawMsg, key) + case "rootCertObjectName": + err = unpopulate(val, "RootCertObjectName", &i.RootCertObjectName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IstioServiceMesh. +func (i IstioServiceMesh) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateAuthority", i.CertificateAuthority) + populate(objectMap, "components", i.Components) + populate(objectMap, "revisions", i.Revisions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IstioServiceMesh. +func (i *IstioServiceMesh) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificateAuthority": + err = unpopulate(val, "CertificateAuthority", &i.CertificateAuthority) + delete(rawMsg, key) + case "components": + err = unpopulate(val, "Components", &i.Components) + delete(rawMsg, key) + case "revisions": + err = unpopulate(val, "Revisions", &i.Revisions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type KubeletConfig. func (k KubeletConfig) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -2629,7 +2858,9 @@ func (m ManagedClusterProperties) MarshalJSON() ([]byte, error) { populate(objectMap, "privateLinkResources", m.PrivateLinkResources) populate(objectMap, "provisioningState", m.ProvisioningState) populate(objectMap, "publicNetworkAccess", m.PublicNetworkAccess) + populate(objectMap, "resourceUID", m.ResourceUID) populate(objectMap, "securityProfile", m.SecurityProfile) + populate(objectMap, "serviceMeshProfile", m.ServiceMeshProfile) populate(objectMap, "servicePrincipalProfile", m.ServicePrincipalProfile) populate(objectMap, "storageProfile", m.StorageProfile) populate(objectMap, "supportPlan", m.SupportPlan) @@ -2738,9 +2969,15 @@ func (m *ManagedClusterProperties) UnmarshalJSON(data []byte) error { case "publicNetworkAccess": err = unpopulate(val, "PublicNetworkAccess", &m.PublicNetworkAccess) delete(rawMsg, key) + case "resourceUID": + err = unpopulate(val, "ResourceUID", &m.ResourceUID) + delete(rawMsg, key) case "securityProfile": err = unpopulate(val, "SecurityProfile", &m.SecurityProfile) delete(rawMsg, key) + case "serviceMeshProfile": + err = unpopulate(val, "ServiceMeshProfile", &m.ServiceMeshProfile) + delete(rawMsg, key) case "servicePrincipalProfile": err = unpopulate(val, "ServicePrincipalProfile", &m.ServicePrincipalProfile) delete(rawMsg, key) @@ -3451,6 +3688,251 @@ func (m *ManagedServiceIdentityUserAssignedIdentitiesValue) UnmarshalJSON(data [ return nil } +// MarshalJSON implements the json.Marshaller interface for type MeshRevision. +func (m MeshRevision) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "compatibleWith", m.CompatibleWith) + populate(objectMap, "revision", m.Revision) + populate(objectMap, "upgrades", m.Upgrades) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshRevision. +func (m *MeshRevision) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "compatibleWith": + err = unpopulate(val, "CompatibleWith", &m.CompatibleWith) + delete(rawMsg, key) + case "revision": + err = unpopulate(val, "Revision", &m.Revision) + delete(rawMsg, key) + case "upgrades": + err = unpopulate(val, "Upgrades", &m.Upgrades) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MeshRevisionProfile. +func (m MeshRevisionProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshRevisionProfile. +func (m *MeshRevisionProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MeshRevisionProfileList. +func (m MeshRevisionProfileList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshRevisionProfileList. +func (m *MeshRevisionProfileList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MeshRevisionProfileProperties. +func (m MeshRevisionProfileProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "meshRevisions", m.MeshRevisions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshRevisionProfileProperties. +func (m *MeshRevisionProfileProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "meshRevisions": + err = unpopulate(val, "MeshRevisions", &m.MeshRevisions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MeshUpgradeProfile. +func (m MeshUpgradeProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshUpgradeProfile. +func (m *MeshUpgradeProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MeshUpgradeProfileList. +func (m MeshUpgradeProfileList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshUpgradeProfileList. +func (m *MeshUpgradeProfileList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MeshUpgradeProfileProperties. +func (m MeshUpgradeProfileProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "compatibleWith", m.CompatibleWith) + populate(objectMap, "revision", m.Revision) + populate(objectMap, "upgrades", m.Upgrades) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MeshUpgradeProfileProperties. +func (m *MeshUpgradeProfileProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "compatibleWith": + err = unpopulate(val, "CompatibleWith", &m.CompatibleWith) + delete(rawMsg, key) + case "revision": + err = unpopulate(val, "Revision", &m.Revision) + delete(rawMsg, key) + case "upgrades": + err = unpopulate(val, "Upgrades", &m.Upgrades) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type NetworkProfile. func (n NetworkProfile) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -4275,6 +4757,37 @@ func (s *Schedule) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ServiceMeshProfile. +func (s ServiceMeshProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "istio", s.Istio) + populate(objectMap, "mode", s.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceMeshProfile. +func (s *ServiceMeshProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "istio": + err = unpopulate(val, "Istio", &s.Istio) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &s.Mode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type Snapshot. func (s Snapshot) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go index 6878e3fa55..26713ee967 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/operations_client.go @@ -39,7 +39,7 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO // NewListPager - Gets a list of operations. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ @@ -71,7 +71,7 @@ func (client *OperationsClient) listCreateRequest(ctx context.Context, options * return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/options.go index 83203afcc4..15de999185 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/options.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/options.go @@ -166,6 +166,18 @@ type ManagedClustersClientGetCommandResultOptions struct { // placeholder for future optional parameters } +// ManagedClustersClientGetMeshRevisionProfileOptions contains the optional parameters for the ManagedClustersClient.GetMeshRevisionProfile +// method. +type ManagedClustersClientGetMeshRevisionProfileOptions struct { + // placeholder for future optional parameters +} + +// ManagedClustersClientGetMeshUpgradeProfileOptions contains the optional parameters for the ManagedClustersClient.GetMeshUpgradeProfile +// method. +type ManagedClustersClientGetMeshUpgradeProfileOptions struct { + // placeholder for future optional parameters +} + // ManagedClustersClientGetOSOptionsOptions contains the optional parameters for the ManagedClustersClient.GetOSOptions method. type ManagedClustersClientGetOSOptionsOptions struct { // The resource type for which the OS options needs to be returned @@ -221,6 +233,18 @@ type ManagedClustersClientListKubernetesVersionsOptions struct { // placeholder for future optional parameters } +// ManagedClustersClientListMeshRevisionProfilesOptions contains the optional parameters for the ManagedClustersClient.NewListMeshRevisionProfilesPager +// method. +type ManagedClustersClientListMeshRevisionProfilesOptions struct { + // placeholder for future optional parameters +} + +// ManagedClustersClientListMeshUpgradeProfilesOptions contains the optional parameters for the ManagedClustersClient.NewListMeshUpgradeProfilesPager +// method. +type ManagedClustersClientListMeshUpgradeProfilesOptions struct { + // placeholder for future optional parameters +} + // ManagedClustersClientListOptions contains the optional parameters for the ManagedClustersClient.NewListPager method. type ManagedClustersClientListOptions struct { // placeholder for future optional parameters diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go index 552efc5bab..27ab66b0dd 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privateendpointconnections_client.go @@ -46,7 +46,7 @@ func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcor // BeginDelete - Deletes a private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - privateEndpointConnectionName - The name of the private endpoint connection. @@ -68,7 +68,7 @@ func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, // Delete - Deletes a private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { var err error req, err := client.deleteCreateRequest(ctx, resourceGroupName, resourceName, privateEndpointConnectionName, options) @@ -110,7 +110,7 @@ func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -119,7 +119,7 @@ func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context. // Get - To learn more about private clusters, see: https://docs.microsoft.com/azure/aks/private-clusters // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - privateEndpointConnectionName - The name of the private endpoint connection. @@ -167,7 +167,7 @@ func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Con return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -185,7 +185,7 @@ func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Res // List - To learn more about private clusters, see: https://docs.microsoft.com/azure/aks/private-clusters // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.List @@ -228,7 +228,7 @@ func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Co return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -246,7 +246,7 @@ func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Re // Update - Updates a private endpoint connection. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - privateEndpointConnectionName - The name of the private endpoint connection. @@ -295,7 +295,7 @@ func (client *PrivateEndpointConnectionsClient) updateCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go index 3f5942c196..b9c987979d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/privatelinkresources_client.go @@ -46,7 +46,7 @@ func NewPrivateLinkResourcesClient(subscriptionID string, credential azcore.Toke // List - To learn more about private clusters, see: https://docs.microsoft.com/azure/aks/private-clusters // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - PrivateLinkResourcesClientListOptions contains the optional parameters for the PrivateLinkResourcesClient.List @@ -89,7 +89,7 @@ func (client *PrivateLinkResourcesClient) listCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go index 3a85ee711d..f480bb5f8b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/resolveprivatelinkserviceid_client.go @@ -46,7 +46,7 @@ func NewResolvePrivateLinkServiceIDClient(subscriptionID string, credential azco // POST - Gets the private link service ID for the specified managed cluster. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - Parameters required in order to resolve a private link service ID. @@ -90,7 +90,7 @@ func (client *ResolvePrivateLinkServiceIDClient) postCreateRequest(ctx context.C return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/response_types.go index cdf2050855..199da37172 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/response_types.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/response_types.go @@ -110,6 +110,18 @@ type ManagedClustersClientGetCommandResultResponse struct { Location *string } +// ManagedClustersClientGetMeshRevisionProfileResponse contains the response from method ManagedClustersClient.GetMeshRevisionProfile. +type ManagedClustersClientGetMeshRevisionProfileResponse struct { + // Mesh revision profile for a mesh. + MeshRevisionProfile +} + +// ManagedClustersClientGetMeshUpgradeProfileResponse contains the response from method ManagedClustersClient.GetMeshUpgradeProfile. +type ManagedClustersClientGetMeshUpgradeProfileResponse struct { + // Upgrade profile for given mesh. + MeshUpgradeProfile +} + // ManagedClustersClientGetOSOptionsResponse contains the response from method ManagedClustersClient.GetOSOptions. type ManagedClustersClientGetOSOptionsResponse struct { // The OS option profile. @@ -158,6 +170,18 @@ type ManagedClustersClientListKubernetesVersionsResponse struct { KubernetesVersionListResult } +// ManagedClustersClientListMeshRevisionProfilesResponse contains the response from method ManagedClustersClient.NewListMeshRevisionProfilesPager. +type ManagedClustersClientListMeshRevisionProfilesResponse struct { + // Holds an array of MeshRevisionsProfiles + MeshRevisionProfileList +} + +// ManagedClustersClientListMeshUpgradeProfilesResponse contains the response from method ManagedClustersClient.NewListMeshUpgradeProfilesPager. +type ManagedClustersClientListMeshUpgradeProfilesResponse struct { + // Holds an array of MeshUpgradeProfiles + MeshUpgradeProfileList +} + // ManagedClustersClientListOutboundNetworkDependenciesEndpointsResponse contains the response from method ManagedClustersClient.NewListOutboundNetworkDependenciesEndpointsPager. type ManagedClustersClientListOutboundNetworkDependenciesEndpointsResponse struct { // Collection of OutboundEnvironmentEndpoint diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go index 77f874e4e1..40f8bf094f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4/snapshots_client.go @@ -46,7 +46,7 @@ func NewSnapshotsClient(subscriptionID string, credential azcore.TokenCredential // CreateOrUpdate - Creates or updates a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - The snapshot to create or update. @@ -90,7 +90,7 @@ func (client *SnapshotsClient) createOrUpdateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { @@ -111,7 +111,7 @@ func (client *SnapshotsClient) createOrUpdateHandleResponse(resp *http.Response) // Delete - Deletes a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - SnapshotsClientDeleteOptions contains the optional parameters for the SnapshotsClient.Delete method. @@ -152,7 +152,7 @@ func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -161,7 +161,7 @@ func (client *SnapshotsClient) deleteCreateRequest(ctx context.Context, resource // Get - Gets a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - options - SnapshotsClientGetOptions contains the optional parameters for the SnapshotsClient.Get method. @@ -203,7 +203,7 @@ func (client *SnapshotsClient) getCreateRequest(ctx context.Context, resourceGro return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -220,7 +220,7 @@ func (client *SnapshotsClient) getHandleResponse(resp *http.Response) (Snapshots // NewListPager - Gets a list of snapshots in the specified subscription. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - options - SnapshotsClientListOptions contains the optional parameters for the SnapshotsClient.NewListPager method. func (client *SnapshotsClient) NewListPager(options *SnapshotsClientListOptions) *runtime.Pager[SnapshotsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[SnapshotsClientListResponse]{ @@ -262,7 +262,7 @@ func (client *SnapshotsClient) listCreateRequest(ctx context.Context, options *S return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -279,7 +279,7 @@ func (client *SnapshotsClient) listHandleResponse(resp *http.Response) (Snapshot // NewListByResourceGroupPager - Lists snapshots in the specified subscription and resource group. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - options - SnapshotsClientListByResourceGroupOptions contains the optional parameters for the SnapshotsClient.NewListByResourceGroupPager // method. @@ -327,7 +327,7 @@ func (client *SnapshotsClient) listByResourceGroupCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -345,7 +345,7 @@ func (client *SnapshotsClient) listByResourceGroupHandleResponse(resp *http.Resp // UpdateTags - Updates tags on a snapshot. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2023-07-01 +// Generated from API version 2023-08-01 // - resourceGroupName - The name of the resource group. The name is case insensitive. // - resourceName - The name of the managed cluster resource. // - parameters - Parameters supplied to the Update snapshot Tags operation. @@ -388,7 +388,7 @@ func (client *SnapshotsClient) updateTagsCreateRequest(ctx context.Context, reso return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2023-07-01") + reqQP.Set("api-version", "2023-08-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/CHANGELOG.md new file mode 100644 index 0000000000..b0776fae40 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/CHANGELOG.md @@ -0,0 +1,77 @@ +# Release History + +## 1.3.0 (2023-10-27) +### Features Added + +- New value `ManagedHsmSKUNameCustomB6` added to enum type `ManagedHsmSKUName` +- New enum type `ManagedServiceIdentityType` with values `ManagedServiceIdentityTypeNone`, `ManagedServiceIdentityTypeSystemAssigned`, `ManagedServiceIdentityTypeSystemAssignedUserAssigned`, `ManagedServiceIdentityTypeUserAssigned` +- New struct `ManagedServiceIdentity` +- New struct `UserAssignedIdentity` +- New field `Identity` in struct `MHSMPrivateEndpointConnection` +- New field `Identity` in struct `MHSMPrivateLinkResource` +- New field `Identity` in struct `ManagedHsm` + + +## 1.2.0 (2023-04-28) +### Features Added + +- New value `JSONWebKeyOperationRelease` added to enum type `JSONWebKeyOperation` +- New value `KeyPermissionsGetrotationpolicy`, `KeyPermissionsRelease`, `KeyPermissionsRotate`, `KeyPermissionsSetrotationpolicy` added to enum type `KeyPermissions` +- New enum type `ActivationStatus` with values `ActivationStatusActive`, `ActivationStatusFailed`, `ActivationStatusNotActivated`, `ActivationStatusUnknown` +- New enum type `GeoReplicationRegionProvisioningState` with values `GeoReplicationRegionProvisioningStateCleanup`, `GeoReplicationRegionProvisioningStateDeleting`, `GeoReplicationRegionProvisioningStateFailed`, `GeoReplicationRegionProvisioningStatePreprovisioning`, `GeoReplicationRegionProvisioningStateProvisioning`, `GeoReplicationRegionProvisioningStateSucceeded` +- New enum type `KeyRotationPolicyActionType` with values `KeyRotationPolicyActionTypeNotify`, `KeyRotationPolicyActionTypeRotate` +- New function `*ClientFactory.NewMHSMRegionsClient() *MHSMRegionsClient` +- New function `*ClientFactory.NewManagedHsmKeysClient() *ManagedHsmKeysClient` +- New function `NewMHSMRegionsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*MHSMRegionsClient, error)` +- New function `*MHSMRegionsClient.NewListByResourcePager(string, string, *MHSMRegionsClientListByResourceOptions) *runtime.Pager[MHSMRegionsClientListByResourceResponse]` +- New function `NewManagedHsmKeysClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagedHsmKeysClient, error)` +- New function `*ManagedHsmKeysClient.CreateIfNotExist(context.Context, string, string, string, ManagedHsmKeyCreateParameters, *ManagedHsmKeysClientCreateIfNotExistOptions) (ManagedHsmKeysClientCreateIfNotExistResponse, error)` +- New function `*ManagedHsmKeysClient.Get(context.Context, string, string, string, *ManagedHsmKeysClientGetOptions) (ManagedHsmKeysClientGetResponse, error)` +- New function `*ManagedHsmKeysClient.GetVersion(context.Context, string, string, string, string, *ManagedHsmKeysClientGetVersionOptions) (ManagedHsmKeysClientGetVersionResponse, error)` +- New function `*ManagedHsmKeysClient.NewListPager(string, string, *ManagedHsmKeysClientListOptions) *runtime.Pager[ManagedHsmKeysClientListResponse]` +- New function `*ManagedHsmKeysClient.NewListVersionsPager(string, string, string, *ManagedHsmKeysClientListVersionsOptions) *runtime.Pager[ManagedHsmKeysClientListVersionsResponse]` +- New function `*ManagedHsmsClient.CheckMhsmNameAvailability(context.Context, CheckMhsmNameAvailabilityParameters, *ManagedHsmsClientCheckMhsmNameAvailabilityOptions) (ManagedHsmsClientCheckMhsmNameAvailabilityResponse, error)` +- New struct `Action` +- New struct `CheckMhsmNameAvailabilityParameters` +- New struct `CheckMhsmNameAvailabilityResult` +- New struct `KeyReleasePolicy` +- New struct `KeyRotationPolicyAttributes` +- New struct `LifetimeAction` +- New struct `MHSMGeoReplicatedRegion` +- New struct `MHSMRegionsListResult` +- New struct `ManagedHSMSecurityDomainProperties` +- New struct `ManagedHsmAction` +- New struct `ManagedHsmKey` +- New struct `ManagedHsmKeyAttributes` +- New struct `ManagedHsmKeyCreateParameters` +- New struct `ManagedHsmKeyListResult` +- New struct `ManagedHsmKeyProperties` +- New struct `ManagedHsmKeyReleasePolicy` +- New struct `ManagedHsmKeyRotationPolicyAttributes` +- New struct `ManagedHsmLifetimeAction` +- New struct `ManagedHsmRotationPolicy` +- New struct `ManagedHsmTrigger` +- New struct `ProxyResourceWithoutSystemData` +- New struct `RotationPolicy` +- New struct `Trigger` +- New field `ReleasePolicy` in struct `KeyProperties` +- New field `RotationPolicy` in struct `KeyProperties` +- New field `Etag` in struct `MHSMPrivateEndpointConnectionItem` +- New field `ID` in struct `MHSMPrivateEndpointConnectionItem` +- New field `Regions` in struct `ManagedHsmProperties` +- New field `SecurityDomainProperties` in struct `ManagedHsmProperties` + + +## 1.1.0 (2023-04-06) +### Features Added + +- New struct `ClientFactory` which is a client factory used to create any client in this module + + +## 1.0.0 (2022-05-16) + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html) since version 1.0.0, which contains breaking changes. + +To migrate the existing applications to the latest version, please refer to [Migration Guide](https://aka.ms/azsdk/go/mgmt/migration). + +To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt). \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/LICENSE.txt new file mode 100644 index 0000000000..dc0c2ffb3d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/README.md new file mode 100644 index 0000000000..11dbffa467 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/README.md @@ -0,0 +1,91 @@ +# Azure Key Vault Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault) + +The `armkeyvault` module provides operations for working with Azure Key Vault. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/keyvault/armkeyvault) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 or above (You could download and install the latest version of Go from [here](https://go.dev/doc/install). It will replace the existing Go on your machine. If you want to install multiple Go versions on the same machine, you could refer this [doc](https://go.dev/doc/manage-install).) + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Key Vault module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Key Vault. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Client Factory + +Azure Key Vault module consists of one or more clients. We provide a client factory which could be used to create any client in this module. + +```go +clientFactory, err := armkeyvault.NewClientFactory(, cred, nil) +``` + +You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +```go +options := arm.ClientOptions { + ClientOptions: azcore.ClientOptions { + Cloud: cloud.AzureChina, + }, +} +clientFactory, err := armkeyvault.NewClientFactory(, cred, &options) +``` + +## Clients + +A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. + +```go +client := clientFactory.NewVaultsClient() +``` + +## More sample code + +- [Key](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/keyvault/key) +- [Secret](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/keyvault/secret) +- [Vault](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/keyvault/vault) + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Key Vault` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/assets.json new file mode 100644 index 0000000000..0849394ce6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "go", + "TagPrefix": "go/resourcemanager/keyvault/armkeyvault", + "Tag": "go/resourcemanager/keyvault/armkeyvault_5d94ebc7b4" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/autorest.md new file mode 100644 index 0000000000..15e504d5c4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/autorest.md @@ -0,0 +1,15 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/9ec0fcc278aa2128c4fbb2b8a1aa93432d72cce0/specification/keyvault/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/9ec0fcc278aa2128c4fbb2b8a1aa93432d72cce0/specification/keyvault/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 1.3.0 +modelerfour: + seal-single-value-enum-by-default: true +tag: package-2023-07 +``` \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/build.go new file mode 100644 index 0000000000..ef03d76746 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -removeUnreferencedTypes resourcemanager/keyvault/armkeyvault + +package armkeyvault diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/ci.yml new file mode 100644 index 0000000000..db5bcb593d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/ci.yml @@ -0,0 +1,28 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/keyvault/armkeyvault/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/keyvault/armkeyvault/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/keyvault/armkeyvault' diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/client_factory.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/client_factory.go new file mode 100644 index 0000000000..d5f33c14a1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/client_factory.go @@ -0,0 +1,94 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + credential azcore.TokenCredential + options *arm.ClientOptions +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + _, err := arm.NewClient(moduleName+".ClientFactory", moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, credential: credential, + options: options.Clone(), + }, nil +} + +func (c *ClientFactory) NewKeysClient() *KeysClient { + subClient, _ := NewKeysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewMHSMPrivateEndpointConnectionsClient() *MHSMPrivateEndpointConnectionsClient { + subClient, _ := NewMHSMPrivateEndpointConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewMHSMPrivateLinkResourcesClient() *MHSMPrivateLinkResourcesClient { + subClient, _ := NewMHSMPrivateLinkResourcesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewMHSMRegionsClient() *MHSMRegionsClient { + subClient, _ := NewMHSMRegionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewManagedHsmKeysClient() *ManagedHsmKeysClient { + subClient, _ := NewManagedHsmKeysClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewManagedHsmsClient() *ManagedHsmsClient { + subClient, _ := NewManagedHsmsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + subClient, _ := NewOperationsClient(c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewPrivateEndpointConnectionsClient() *PrivateEndpointConnectionsClient { + subClient, _ := NewPrivateEndpointConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewPrivateLinkResourcesClient() *PrivateLinkResourcesClient { + subClient, _ := NewPrivateLinkResourcesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewSecretsClient() *SecretsClient { + subClient, _ := NewSecretsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +func (c *ClientFactory) NewVaultsClient() *VaultsClient { + subClient, _ := NewVaultsClient(c.subscriptionID, c.credential, c.options) + return subClient +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/constants.go new file mode 100644 index 0000000000..92c123908d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/constants.go @@ -0,0 +1,647 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +const ( + moduleName = "armkeyvault" + moduleVersion = "v1.3.0" +) + +type AccessPolicyUpdateKind string + +const ( + AccessPolicyUpdateKindAdd AccessPolicyUpdateKind = "add" + AccessPolicyUpdateKindRemove AccessPolicyUpdateKind = "remove" + AccessPolicyUpdateKindReplace AccessPolicyUpdateKind = "replace" +) + +// PossibleAccessPolicyUpdateKindValues returns the possible values for the AccessPolicyUpdateKind const type. +func PossibleAccessPolicyUpdateKindValues() []AccessPolicyUpdateKind { + return []AccessPolicyUpdateKind{ + AccessPolicyUpdateKindAdd, + AccessPolicyUpdateKindRemove, + AccessPolicyUpdateKindReplace, + } +} + +// ActionsRequired - A message indicating if changes on the service provider require any updates on the consumer. +type ActionsRequired string + +const ( + ActionsRequiredNone ActionsRequired = "None" +) + +// PossibleActionsRequiredValues returns the possible values for the ActionsRequired const type. +func PossibleActionsRequiredValues() []ActionsRequired { + return []ActionsRequired{ + ActionsRequiredNone, + } +} + +// ActivationStatus - Activation Status +type ActivationStatus string + +const ( + // ActivationStatusActive - The managed HSM Pool is active. + ActivationStatusActive ActivationStatus = "Active" + // ActivationStatusFailed - Failed to activate managed hsm. + ActivationStatusFailed ActivationStatus = "Failed" + // ActivationStatusNotActivated - The managed HSM Pool is not yet activated. + ActivationStatusNotActivated ActivationStatus = "NotActivated" + // ActivationStatusUnknown - An unknown error occurred while activating managed hsm. + ActivationStatusUnknown ActivationStatus = "Unknown" +) + +// PossibleActivationStatusValues returns the possible values for the ActivationStatus const type. +func PossibleActivationStatusValues() []ActivationStatus { + return []ActivationStatus{ + ActivationStatusActive, + ActivationStatusFailed, + ActivationStatusNotActivated, + ActivationStatusUnknown, + } +} + +type CertificatePermissions string + +const ( + CertificatePermissionsAll CertificatePermissions = "all" + CertificatePermissionsBackup CertificatePermissions = "backup" + CertificatePermissionsCreate CertificatePermissions = "create" + CertificatePermissionsDelete CertificatePermissions = "delete" + CertificatePermissionsDeleteissuers CertificatePermissions = "deleteissuers" + CertificatePermissionsGet CertificatePermissions = "get" + CertificatePermissionsGetissuers CertificatePermissions = "getissuers" + CertificatePermissionsImport CertificatePermissions = "import" + CertificatePermissionsList CertificatePermissions = "list" + CertificatePermissionsListissuers CertificatePermissions = "listissuers" + CertificatePermissionsManagecontacts CertificatePermissions = "managecontacts" + CertificatePermissionsManageissuers CertificatePermissions = "manageissuers" + CertificatePermissionsPurge CertificatePermissions = "purge" + CertificatePermissionsRecover CertificatePermissions = "recover" + CertificatePermissionsRestore CertificatePermissions = "restore" + CertificatePermissionsSetissuers CertificatePermissions = "setissuers" + CertificatePermissionsUpdate CertificatePermissions = "update" +) + +// PossibleCertificatePermissionsValues returns the possible values for the CertificatePermissions const type. +func PossibleCertificatePermissionsValues() []CertificatePermissions { + return []CertificatePermissions{ + CertificatePermissionsAll, + CertificatePermissionsBackup, + CertificatePermissionsCreate, + CertificatePermissionsDelete, + CertificatePermissionsDeleteissuers, + CertificatePermissionsGet, + CertificatePermissionsGetissuers, + CertificatePermissionsImport, + CertificatePermissionsList, + CertificatePermissionsListissuers, + CertificatePermissionsManagecontacts, + CertificatePermissionsManageissuers, + CertificatePermissionsPurge, + CertificatePermissionsRecover, + CertificatePermissionsRestore, + CertificatePermissionsSetissuers, + CertificatePermissionsUpdate, + } +} + +// CreateMode - The vault's create mode to indicate whether the vault need to be recovered or not. +type CreateMode string + +const ( + CreateModeDefault CreateMode = "default" + CreateModeRecover CreateMode = "recover" +) + +// PossibleCreateModeValues returns the possible values for the CreateMode const type. +func PossibleCreateModeValues() []CreateMode { + return []CreateMode{ + CreateModeDefault, + CreateModeRecover, + } +} + +// DeletionRecoveryLevel - The deletion recovery level currently in effect for the object. If it contains 'Purgeable', then +// the object can be permanently deleted by a privileged user; otherwise, only the system can purge the +// object at the end of the retention interval. +type DeletionRecoveryLevel string + +const ( + DeletionRecoveryLevelPurgeable DeletionRecoveryLevel = "Purgeable" + DeletionRecoveryLevelRecoverable DeletionRecoveryLevel = "Recoverable" + DeletionRecoveryLevelRecoverableProtectedSubscription DeletionRecoveryLevel = "Recoverable+ProtectedSubscription" + DeletionRecoveryLevelRecoverablePurgeable DeletionRecoveryLevel = "Recoverable+Purgeable" +) + +// PossibleDeletionRecoveryLevelValues returns the possible values for the DeletionRecoveryLevel const type. +func PossibleDeletionRecoveryLevelValues() []DeletionRecoveryLevel { + return []DeletionRecoveryLevel{ + DeletionRecoveryLevelPurgeable, + DeletionRecoveryLevelRecoverable, + DeletionRecoveryLevelRecoverableProtectedSubscription, + DeletionRecoveryLevelRecoverablePurgeable, + } +} + +// GeoReplicationRegionProvisioningState - The current provisioning state. +type GeoReplicationRegionProvisioningState string + +const ( + GeoReplicationRegionProvisioningStateCleanup GeoReplicationRegionProvisioningState = "Cleanup" + GeoReplicationRegionProvisioningStateDeleting GeoReplicationRegionProvisioningState = "Deleting" + GeoReplicationRegionProvisioningStateFailed GeoReplicationRegionProvisioningState = "Failed" + GeoReplicationRegionProvisioningStatePreprovisioning GeoReplicationRegionProvisioningState = "Preprovisioning" + GeoReplicationRegionProvisioningStateProvisioning GeoReplicationRegionProvisioningState = "Provisioning" + GeoReplicationRegionProvisioningStateSucceeded GeoReplicationRegionProvisioningState = "Succeeded" +) + +// PossibleGeoReplicationRegionProvisioningStateValues returns the possible values for the GeoReplicationRegionProvisioningState const type. +func PossibleGeoReplicationRegionProvisioningStateValues() []GeoReplicationRegionProvisioningState { + return []GeoReplicationRegionProvisioningState{ + GeoReplicationRegionProvisioningStateCleanup, + GeoReplicationRegionProvisioningStateDeleting, + GeoReplicationRegionProvisioningStateFailed, + GeoReplicationRegionProvisioningStatePreprovisioning, + GeoReplicationRegionProvisioningStateProvisioning, + GeoReplicationRegionProvisioningStateSucceeded, + } +} + +// IdentityType - The type of identity. +type IdentityType string + +const ( + IdentityTypeApplication IdentityType = "Application" + IdentityTypeKey IdentityType = "Key" + IdentityTypeManagedIdentity IdentityType = "ManagedIdentity" + IdentityTypeUser IdentityType = "User" +) + +// PossibleIdentityTypeValues returns the possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{ + IdentityTypeApplication, + IdentityTypeKey, + IdentityTypeManagedIdentity, + IdentityTypeUser, + } +} + +// JSONWebKeyCurveName - The elliptic curve name. For valid values, see JsonWebKeyCurveName. +type JSONWebKeyCurveName string + +const ( + JSONWebKeyCurveNameP256 JSONWebKeyCurveName = "P-256" + JSONWebKeyCurveNameP256K JSONWebKeyCurveName = "P-256K" + JSONWebKeyCurveNameP384 JSONWebKeyCurveName = "P-384" + JSONWebKeyCurveNameP521 JSONWebKeyCurveName = "P-521" +) + +// PossibleJSONWebKeyCurveNameValues returns the possible values for the JSONWebKeyCurveName const type. +func PossibleJSONWebKeyCurveNameValues() []JSONWebKeyCurveName { + return []JSONWebKeyCurveName{ + JSONWebKeyCurveNameP256, + JSONWebKeyCurveNameP256K, + JSONWebKeyCurveNameP384, + JSONWebKeyCurveNameP521, + } +} + +// JSONWebKeyOperation - The permitted JSON web key operations of the key. For more information, see JsonWebKeyOperation. +type JSONWebKeyOperation string + +const ( + JSONWebKeyOperationDecrypt JSONWebKeyOperation = "decrypt" + JSONWebKeyOperationEncrypt JSONWebKeyOperation = "encrypt" + JSONWebKeyOperationImport JSONWebKeyOperation = "import" + JSONWebKeyOperationRelease JSONWebKeyOperation = "release" + JSONWebKeyOperationSign JSONWebKeyOperation = "sign" + JSONWebKeyOperationUnwrapKey JSONWebKeyOperation = "unwrapKey" + JSONWebKeyOperationVerify JSONWebKeyOperation = "verify" + JSONWebKeyOperationWrapKey JSONWebKeyOperation = "wrapKey" +) + +// PossibleJSONWebKeyOperationValues returns the possible values for the JSONWebKeyOperation const type. +func PossibleJSONWebKeyOperationValues() []JSONWebKeyOperation { + return []JSONWebKeyOperation{ + JSONWebKeyOperationDecrypt, + JSONWebKeyOperationEncrypt, + JSONWebKeyOperationImport, + JSONWebKeyOperationRelease, + JSONWebKeyOperationSign, + JSONWebKeyOperationUnwrapKey, + JSONWebKeyOperationVerify, + JSONWebKeyOperationWrapKey, + } +} + +// JSONWebKeyType - The type of the key. For valid values, see JsonWebKeyType. +type JSONWebKeyType string + +const ( + JSONWebKeyTypeEC JSONWebKeyType = "EC" + JSONWebKeyTypeECHSM JSONWebKeyType = "EC-HSM" + JSONWebKeyTypeRSA JSONWebKeyType = "RSA" + JSONWebKeyTypeRSAHSM JSONWebKeyType = "RSA-HSM" +) + +// PossibleJSONWebKeyTypeValues returns the possible values for the JSONWebKeyType const type. +func PossibleJSONWebKeyTypeValues() []JSONWebKeyType { + return []JSONWebKeyType{ + JSONWebKeyTypeEC, + JSONWebKeyTypeECHSM, + JSONWebKeyTypeRSA, + JSONWebKeyTypeRSAHSM, + } +} + +type KeyPermissions string + +const ( + KeyPermissionsAll KeyPermissions = "all" + KeyPermissionsBackup KeyPermissions = "backup" + KeyPermissionsCreate KeyPermissions = "create" + KeyPermissionsDecrypt KeyPermissions = "decrypt" + KeyPermissionsDelete KeyPermissions = "delete" + KeyPermissionsEncrypt KeyPermissions = "encrypt" + KeyPermissionsGet KeyPermissions = "get" + KeyPermissionsGetrotationpolicy KeyPermissions = "getrotationpolicy" + KeyPermissionsImport KeyPermissions = "import" + KeyPermissionsList KeyPermissions = "list" + KeyPermissionsPurge KeyPermissions = "purge" + KeyPermissionsRecover KeyPermissions = "recover" + KeyPermissionsRelease KeyPermissions = "release" + KeyPermissionsRestore KeyPermissions = "restore" + KeyPermissionsRotate KeyPermissions = "rotate" + KeyPermissionsSetrotationpolicy KeyPermissions = "setrotationpolicy" + KeyPermissionsSign KeyPermissions = "sign" + KeyPermissionsUnwrapKey KeyPermissions = "unwrapKey" + KeyPermissionsUpdate KeyPermissions = "update" + KeyPermissionsVerify KeyPermissions = "verify" + KeyPermissionsWrapKey KeyPermissions = "wrapKey" +) + +// PossibleKeyPermissionsValues returns the possible values for the KeyPermissions const type. +func PossibleKeyPermissionsValues() []KeyPermissions { + return []KeyPermissions{ + KeyPermissionsAll, + KeyPermissionsBackup, + KeyPermissionsCreate, + KeyPermissionsDecrypt, + KeyPermissionsDelete, + KeyPermissionsEncrypt, + KeyPermissionsGet, + KeyPermissionsGetrotationpolicy, + KeyPermissionsImport, + KeyPermissionsList, + KeyPermissionsPurge, + KeyPermissionsRecover, + KeyPermissionsRelease, + KeyPermissionsRestore, + KeyPermissionsRotate, + KeyPermissionsSetrotationpolicy, + KeyPermissionsSign, + KeyPermissionsUnwrapKey, + KeyPermissionsUpdate, + KeyPermissionsVerify, + KeyPermissionsWrapKey, + } +} + +// KeyRotationPolicyActionType - The type of action. +type KeyRotationPolicyActionType string + +const ( + KeyRotationPolicyActionTypeNotify KeyRotationPolicyActionType = "notify" + KeyRotationPolicyActionTypeRotate KeyRotationPolicyActionType = "rotate" +) + +// PossibleKeyRotationPolicyActionTypeValues returns the possible values for the KeyRotationPolicyActionType const type. +func PossibleKeyRotationPolicyActionTypeValues() []KeyRotationPolicyActionType { + return []KeyRotationPolicyActionType{ + KeyRotationPolicyActionTypeNotify, + KeyRotationPolicyActionTypeRotate, + } +} + +// ManagedHsmSKUFamily - SKU Family of the managed HSM Pool +type ManagedHsmSKUFamily string + +const ( + ManagedHsmSKUFamilyB ManagedHsmSKUFamily = "B" +) + +// PossibleManagedHsmSKUFamilyValues returns the possible values for the ManagedHsmSKUFamily const type. +func PossibleManagedHsmSKUFamilyValues() []ManagedHsmSKUFamily { + return []ManagedHsmSKUFamily{ + ManagedHsmSKUFamilyB, + } +} + +// ManagedHsmSKUName - SKU of the managed HSM Pool +type ManagedHsmSKUName string + +const ( + ManagedHsmSKUNameCustomB32 ManagedHsmSKUName = "Custom_B32" + ManagedHsmSKUNameCustomB6 ManagedHsmSKUName = "Custom_B6" + ManagedHsmSKUNameStandardB1 ManagedHsmSKUName = "Standard_B1" +) + +// PossibleManagedHsmSKUNameValues returns the possible values for the ManagedHsmSKUName const type. +func PossibleManagedHsmSKUNameValues() []ManagedHsmSKUName { + return []ManagedHsmSKUName{ + ManagedHsmSKUNameCustomB32, + ManagedHsmSKUNameCustomB6, + ManagedHsmSKUNameStandardB1, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// NetworkRuleAction - The default action when no rule from ipRules and from virtualNetworkRules match. This is only used +// after the bypass property has been evaluated. +type NetworkRuleAction string + +const ( + NetworkRuleActionAllow NetworkRuleAction = "Allow" + NetworkRuleActionDeny NetworkRuleAction = "Deny" +) + +// PossibleNetworkRuleActionValues returns the possible values for the NetworkRuleAction const type. +func PossibleNetworkRuleActionValues() []NetworkRuleAction { + return []NetworkRuleAction{ + NetworkRuleActionAllow, + NetworkRuleActionDeny, + } +} + +// NetworkRuleBypassOptions - Tells what traffic can bypass network rules. This can be 'AzureServices' or 'None'. If not specified +// the default is 'AzureServices'. +type NetworkRuleBypassOptions string + +const ( + NetworkRuleBypassOptionsAzureServices NetworkRuleBypassOptions = "AzureServices" + NetworkRuleBypassOptionsNone NetworkRuleBypassOptions = "None" +) + +// PossibleNetworkRuleBypassOptionsValues returns the possible values for the NetworkRuleBypassOptions const type. +func PossibleNetworkRuleBypassOptionsValues() []NetworkRuleBypassOptions { + return []NetworkRuleBypassOptions{ + NetworkRuleBypassOptionsAzureServices, + NetworkRuleBypassOptionsNone, + } +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateDisconnected PrivateEndpointConnectionProvisioningState = "Disconnected" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" + PrivateEndpointConnectionProvisioningStateUpdating PrivateEndpointConnectionProvisioningState = "Updating" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateDisconnected, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + PrivateEndpointConnectionProvisioningStateUpdating, + } +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + PrivateEndpointServiceConnectionStatusDisconnected PrivateEndpointServiceConnectionStatus = "Disconnected" + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusDisconnected, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// ProvisioningState - Provisioning state. +type ProvisioningState string + +const ( + // ProvisioningStateActivated - The managed HSM pool is ready for normal use. + ProvisioningStateActivated ProvisioningState = "Activated" + // ProvisioningStateDeleting - The managed HSM Pool is currently being deleted. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Provisioning of the managed HSM Pool has failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateProvisioning - The managed HSM Pool is currently being provisioned. + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateRestoring - The managed HSM pool is being restored from full HSM backup. + ProvisioningStateRestoring ProvisioningState = "Restoring" + // ProvisioningStateSecurityDomainRestore - The managed HSM pool is waiting for a security domain restore action. + ProvisioningStateSecurityDomainRestore ProvisioningState = "SecurityDomainRestore" + // ProvisioningStateSucceeded - The managed HSM Pool has been full provisioned. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - The managed HSM Pool is currently being updated. + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateActivated, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateRestoring, + ProvisioningStateSecurityDomainRestore, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// PublicNetworkAccess - Control permission to the managed HSM from public networks. +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// Reason - The reason that a vault name could not be used. The Reason element is only returned if NameAvailable is false. +type Reason string + +const ( + ReasonAccountNameInvalid Reason = "AccountNameInvalid" + ReasonAlreadyExists Reason = "AlreadyExists" +) + +// PossibleReasonValues returns the possible values for the Reason const type. +func PossibleReasonValues() []Reason { + return []Reason{ + ReasonAccountNameInvalid, + ReasonAlreadyExists, + } +} + +// SKUFamily - SKU family name +type SKUFamily string + +const ( + SKUFamilyA SKUFamily = "A" +) + +// PossibleSKUFamilyValues returns the possible values for the SKUFamily const type. +func PossibleSKUFamilyValues() []SKUFamily { + return []SKUFamily{ + SKUFamilyA, + } +} + +// SKUName - SKU name to specify whether the key vault is a standard vault or a premium vault. +type SKUName string + +const ( + SKUNamePremium SKUName = "premium" + SKUNameStandard SKUName = "standard" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNamePremium, + SKUNameStandard, + } +} + +type SecretPermissions string + +const ( + SecretPermissionsAll SecretPermissions = "all" + SecretPermissionsBackup SecretPermissions = "backup" + SecretPermissionsDelete SecretPermissions = "delete" + SecretPermissionsGet SecretPermissions = "get" + SecretPermissionsList SecretPermissions = "list" + SecretPermissionsPurge SecretPermissions = "purge" + SecretPermissionsRecover SecretPermissions = "recover" + SecretPermissionsRestore SecretPermissions = "restore" + SecretPermissionsSet SecretPermissions = "set" +) + +// PossibleSecretPermissionsValues returns the possible values for the SecretPermissions const type. +func PossibleSecretPermissionsValues() []SecretPermissions { + return []SecretPermissions{ + SecretPermissionsAll, + SecretPermissionsBackup, + SecretPermissionsDelete, + SecretPermissionsGet, + SecretPermissionsList, + SecretPermissionsPurge, + SecretPermissionsRecover, + SecretPermissionsRestore, + SecretPermissionsSet, + } +} + +type StoragePermissions string + +const ( + StoragePermissionsAll StoragePermissions = "all" + StoragePermissionsBackup StoragePermissions = "backup" + StoragePermissionsDelete StoragePermissions = "delete" + StoragePermissionsDeletesas StoragePermissions = "deletesas" + StoragePermissionsGet StoragePermissions = "get" + StoragePermissionsGetsas StoragePermissions = "getsas" + StoragePermissionsList StoragePermissions = "list" + StoragePermissionsListsas StoragePermissions = "listsas" + StoragePermissionsPurge StoragePermissions = "purge" + StoragePermissionsRecover StoragePermissions = "recover" + StoragePermissionsRegeneratekey StoragePermissions = "regeneratekey" + StoragePermissionsRestore StoragePermissions = "restore" + StoragePermissionsSet StoragePermissions = "set" + StoragePermissionsSetsas StoragePermissions = "setsas" + StoragePermissionsUpdate StoragePermissions = "update" +) + +// PossibleStoragePermissionsValues returns the possible values for the StoragePermissions const type. +func PossibleStoragePermissionsValues() []StoragePermissions { + return []StoragePermissions{ + StoragePermissionsAll, + StoragePermissionsBackup, + StoragePermissionsDelete, + StoragePermissionsDeletesas, + StoragePermissionsGet, + StoragePermissionsGetsas, + StoragePermissionsList, + StoragePermissionsListsas, + StoragePermissionsPurge, + StoragePermissionsRecover, + StoragePermissionsRegeneratekey, + StoragePermissionsRestore, + StoragePermissionsSet, + StoragePermissionsSetsas, + StoragePermissionsUpdate, + } +} + +// VaultProvisioningState - Provisioning state of the vault. +type VaultProvisioningState string + +const ( + VaultProvisioningStateRegisteringDNS VaultProvisioningState = "RegisteringDns" + VaultProvisioningStateSucceeded VaultProvisioningState = "Succeeded" +) + +// PossibleVaultProvisioningStateValues returns the possible values for the VaultProvisioningState const type. +func PossibleVaultProvisioningStateValues() []VaultProvisioningState { + return []VaultProvisioningState{ + VaultProvisioningStateRegisteringDNS, + VaultProvisioningStateSucceeded, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/keys_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/keys_client.go new file mode 100644 index 0000000000..da53437de3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/keys_client.go @@ -0,0 +1,396 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// KeysClient contains the methods for the Keys group. +// Don't use this type directly, use NewKeysClient() instead. +type KeysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewKeysClient creates a new instance of KeysClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewKeysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*KeysClient, error) { + cl, err := arm.NewClient(moduleName+".KeysClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &KeysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateIfNotExist - Creates the first version of a new key if it does not exist. If it already exists, then the existing +// key is returned without any write operations being performed. This API does not create subsequent +// versions, and does not update existing keys. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group which contains the specified key vault. +// - vaultName - The name of the key vault which contains the key to be created. +// - keyName - The name of the key to be created. The value you provide may be copied globally for the purpose of running the +// service. The value provided should not include personally identifiable or sensitive +// information. +// - parameters - The parameters used to create the specified key. +// - options - KeysClientCreateIfNotExistOptions contains the optional parameters for the KeysClient.CreateIfNotExist method. +func (client *KeysClient) CreateIfNotExist(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters, options *KeysClientCreateIfNotExistOptions) (KeysClientCreateIfNotExistResponse, error) { + var err error + req, err := client.createIfNotExistCreateRequest(ctx, resourceGroupName, vaultName, keyName, parameters, options) + if err != nil { + return KeysClientCreateIfNotExistResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeysClientCreateIfNotExistResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeysClientCreateIfNotExistResponse{}, err + } + resp, err := client.createIfNotExistHandleResponse(httpResp) + return resp, err +} + +// createIfNotExistCreateRequest creates the CreateIfNotExist request. +func (client *KeysClient) createIfNotExistCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters, options *KeysClientCreateIfNotExistOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// createIfNotExistHandleResponse handles the CreateIfNotExist response. +func (client *KeysClient) createIfNotExistHandleResponse(resp *http.Response) (KeysClientCreateIfNotExistResponse, error) { + result := KeysClientCreateIfNotExistResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil { + return KeysClientCreateIfNotExistResponse{}, err + } + return result, nil +} + +// Get - Gets the current version of the specified key from the specified key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group which contains the specified key vault. +// - vaultName - The name of the vault which contains the key to be retrieved. +// - keyName - The name of the key to be retrieved. +// - options - KeysClientGetOptions contains the optional parameters for the KeysClient.Get method. +func (client *KeysClient) Get(ctx context.Context, resourceGroupName string, vaultName string, keyName string, options *KeysClientGetOptions) (KeysClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, vaultName, keyName, options) + if err != nil { + return KeysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *KeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, options *KeysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *KeysClient) getHandleResponse(resp *http.Response) (KeysClientGetResponse, error) { + result := KeysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil { + return KeysClientGetResponse{}, err + } + return result, nil +} + +// GetVersion - Gets the specified version of the specified key in the specified key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group which contains the specified key vault. +// - vaultName - The name of the vault which contains the key version to be retrieved. +// - keyName - The name of the key version to be retrieved. +// - keyVersion - The version of the key to be retrieved. +// - options - KeysClientGetVersionOptions contains the optional parameters for the KeysClient.GetVersion method. +func (client *KeysClient) GetVersion(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string, options *KeysClientGetVersionOptions) (KeysClientGetVersionResponse, error) { + var err error + req, err := client.getVersionCreateRequest(ctx, resourceGroupName, vaultName, keyName, keyVersion, options) + if err != nil { + return KeysClientGetVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeysClientGetVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeysClientGetVersionResponse{}, err + } + resp, err := client.getVersionHandleResponse(httpResp) + return resp, err +} + +// getVersionCreateRequest creates the GetVersion request. +func (client *KeysClient) getVersionCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string, options *KeysClientGetVersionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions/{keyVersion}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyVersion}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getVersionHandleResponse handles the GetVersion response. +func (client *KeysClient) getVersionHandleResponse(resp *http.Response) (KeysClientGetVersionResponse, error) { + result := KeysClientGetVersionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil { + return KeysClientGetVersionResponse{}, err + } + return result, nil +} + +// NewListPager - Lists the keys in the specified key vault. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group which contains the specified key vault. +// - vaultName - The name of the vault which contains the keys to be retrieved. +// - options - KeysClientListOptions contains the optional parameters for the KeysClient.NewListPager method. +func (client *KeysClient) NewListPager(resourceGroupName string, vaultName string, options *KeysClientListOptions) *runtime.Pager[KeysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[KeysClientListResponse]{ + More: func(page KeysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *KeysClientListResponse) (KeysClientListResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listCreateRequest(ctx, resourceGroupName, vaultName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return KeysClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeysClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return KeysClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + }) +} + +// listCreateRequest creates the List request. +func (client *KeysClient) listCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *KeysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *KeysClient) listHandleResponse(resp *http.Response) (KeysClientListResponse, error) { + result := KeysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil { + return KeysClientListResponse{}, err + } + return result, nil +} + +// NewListVersionsPager - Lists the versions of the specified key in the specified key vault. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group which contains the specified key vault. +// - vaultName - The name of the vault which contains the key versions to be retrieved. +// - keyName - The name of the key versions to be retrieved. +// - options - KeysClientListVersionsOptions contains the optional parameters for the KeysClient.NewListVersionsPager method. +func (client *KeysClient) NewListVersionsPager(resourceGroupName string, vaultName string, keyName string, options *KeysClientListVersionsOptions) *runtime.Pager[KeysClientListVersionsResponse] { + return runtime.NewPager(runtime.PagingHandler[KeysClientListVersionsResponse]{ + More: func(page KeysClientListVersionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *KeysClientListVersionsResponse) (KeysClientListVersionsResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listVersionsCreateRequest(ctx, resourceGroupName, vaultName, keyName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return KeysClientListVersionsResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeysClientListVersionsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return KeysClientListVersionsResponse{}, runtime.NewResponseError(resp) + } + return client.listVersionsHandleResponse(resp) + }, + }) +} + +// listVersionsCreateRequest creates the ListVersions request. +func (client *KeysClient) listVersionsCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, keyName string, options *KeysClientListVersionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVersionsHandleResponse handles the ListVersions response. +func (client *KeysClient) listVersionsHandleResponse(resp *http.Response) (KeysClientListVersionsResponse, error) { + result := KeysClientListVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil { + return KeysClientListVersionsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsmkeys_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsmkeys_client.go new file mode 100644 index 0000000000..98769a5770 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsmkeys_client.go @@ -0,0 +1,405 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ManagedHsmKeysClient contains the methods for the ManagedHsmKeys group. +// Don't use this type directly, use NewManagedHsmKeysClient() instead. +type ManagedHsmKeysClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagedHsmKeysClient creates a new instance of ManagedHsmKeysClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewManagedHsmKeysClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagedHsmKeysClient, error) { + cl, err := arm.NewClient(moduleName+".ManagedHsmKeysClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagedHsmKeysClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateIfNotExist - Creates the first version of a new key if it does not exist. If it already exists, then the existing +// key is returned without any write operations being performed. This API does not create subsequent +// versions, and does not update existing keys. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - The name of the Managed HSM Pool within the specified resource group. +// - keyName - The name of the key to be created. The value you provide may be copied globally for the purpose of running the +// service. The value provided should not include personally identifiable or sensitive +// information. +// - parameters - The parameters used to create the specified key. +// - options - ManagedHsmKeysClientCreateIfNotExistOptions contains the optional parameters for the ManagedHsmKeysClient.CreateIfNotExist +// method. +func (client *ManagedHsmKeysClient) CreateIfNotExist(ctx context.Context, resourceGroupName string, name string, keyName string, parameters ManagedHsmKeyCreateParameters, options *ManagedHsmKeysClientCreateIfNotExistOptions) (ManagedHsmKeysClientCreateIfNotExistResponse, error) { + var err error + req, err := client.createIfNotExistCreateRequest(ctx, resourceGroupName, name, keyName, parameters, options) + if err != nil { + return ManagedHsmKeysClientCreateIfNotExistResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmKeysClientCreateIfNotExistResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedHsmKeysClientCreateIfNotExistResponse{}, err + } + resp, err := client.createIfNotExistHandleResponse(httpResp) + return resp, err +} + +// createIfNotExistCreateRequest creates the CreateIfNotExist request. +func (client *ManagedHsmKeysClient) createIfNotExistCreateRequest(ctx context.Context, resourceGroupName string, name string, keyName string, parameters ManagedHsmKeyCreateParameters, options *ManagedHsmKeysClientCreateIfNotExistOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/keys/{keyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// createIfNotExistHandleResponse handles the CreateIfNotExist response. +func (client *ManagedHsmKeysClient) createIfNotExistHandleResponse(resp *http.Response) (ManagedHsmKeysClientCreateIfNotExistResponse, error) { + result := ManagedHsmKeysClientCreateIfNotExistResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmKey); err != nil { + return ManagedHsmKeysClientCreateIfNotExistResponse{}, err + } + return result, nil +} + +// Get - Gets the current version of the specified key from the specified managed HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - The name of the Managed HSM Pool within the specified resource group. +// - keyName - The name of the key to be created. The value you provide may be copied globally for the purpose of running the +// service. The value provided should not include personally identifiable or sensitive +// information. +// - options - ManagedHsmKeysClientGetOptions contains the optional parameters for the ManagedHsmKeysClient.Get method. +func (client *ManagedHsmKeysClient) Get(ctx context.Context, resourceGroupName string, name string, keyName string, options *ManagedHsmKeysClientGetOptions) (ManagedHsmKeysClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, name, keyName, options) + if err != nil { + return ManagedHsmKeysClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmKeysClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedHsmKeysClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagedHsmKeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, name string, keyName string, options *ManagedHsmKeysClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/keys/{keyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagedHsmKeysClient) getHandleResponse(resp *http.Response) (ManagedHsmKeysClientGetResponse, error) { + result := ManagedHsmKeysClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmKey); err != nil { + return ManagedHsmKeysClientGetResponse{}, err + } + return result, nil +} + +// GetVersion - Gets the specified version of the specified key in the specified managed HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - The name of the Managed HSM Pool within the specified resource group. +// - keyName - The name of the key to be created. The value you provide may be copied globally for the purpose of running the +// service. The value provided should not include personally identifiable or sensitive +// information. +// - keyVersion - The version of the key to be retrieved. +// - options - ManagedHsmKeysClientGetVersionOptions contains the optional parameters for the ManagedHsmKeysClient.GetVersion +// method. +func (client *ManagedHsmKeysClient) GetVersion(ctx context.Context, resourceGroupName string, name string, keyName string, keyVersion string, options *ManagedHsmKeysClientGetVersionOptions) (ManagedHsmKeysClientGetVersionResponse, error) { + var err error + req, err := client.getVersionCreateRequest(ctx, resourceGroupName, name, keyName, keyVersion, options) + if err != nil { + return ManagedHsmKeysClientGetVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmKeysClientGetVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedHsmKeysClientGetVersionResponse{}, err + } + resp, err := client.getVersionHandleResponse(httpResp) + return resp, err +} + +// getVersionCreateRequest creates the GetVersion request. +func (client *ManagedHsmKeysClient) getVersionCreateRequest(ctx context.Context, resourceGroupName string, name string, keyName string, keyVersion string, options *ManagedHsmKeysClientGetVersionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/keys/{keyName}/versions/{keyVersion}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyVersion}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getVersionHandleResponse handles the GetVersion response. +func (client *ManagedHsmKeysClient) getVersionHandleResponse(resp *http.Response) (ManagedHsmKeysClientGetVersionResponse, error) { + result := ManagedHsmKeysClientGetVersionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmKey); err != nil { + return ManagedHsmKeysClientGetVersionResponse{}, err + } + return result, nil +} + +// NewListPager - Lists the keys in the specified managed HSM. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - The name of the Managed HSM Pool within the specified resource group. +// - options - ManagedHsmKeysClientListOptions contains the optional parameters for the ManagedHsmKeysClient.NewListPager method. +func (client *ManagedHsmKeysClient) NewListPager(resourceGroupName string, name string, options *ManagedHsmKeysClientListOptions) *runtime.Pager[ManagedHsmKeysClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedHsmKeysClientListResponse]{ + More: func(page ManagedHsmKeysClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedHsmKeysClientListResponse) (ManagedHsmKeysClientListResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listCreateRequest(ctx, resourceGroupName, name, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedHsmKeysClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmKeysClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedHsmKeysClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + }) +} + +// listCreateRequest creates the List request. +func (client *ManagedHsmKeysClient) listCreateRequest(ctx context.Context, resourceGroupName string, name string, options *ManagedHsmKeysClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/keys" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ManagedHsmKeysClient) listHandleResponse(resp *http.Response) (ManagedHsmKeysClientListResponse, error) { + result := ManagedHsmKeysClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmKeyListResult); err != nil { + return ManagedHsmKeysClientListResponse{}, err + } + return result, nil +} + +// NewListVersionsPager - Lists the versions of the specified key in the specified managed HSM. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - The name of the Managed HSM Pool within the specified resource group. +// - keyName - The name of the key to be created. The value you provide may be copied globally for the purpose of running the +// service. The value provided should not include personally identifiable or sensitive +// information. +// - options - ManagedHsmKeysClientListVersionsOptions contains the optional parameters for the ManagedHsmKeysClient.NewListVersionsPager +// method. +func (client *ManagedHsmKeysClient) NewListVersionsPager(resourceGroupName string, name string, keyName string, options *ManagedHsmKeysClientListVersionsOptions) *runtime.Pager[ManagedHsmKeysClientListVersionsResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedHsmKeysClientListVersionsResponse]{ + More: func(page ManagedHsmKeysClientListVersionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedHsmKeysClientListVersionsResponse) (ManagedHsmKeysClientListVersionsResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listVersionsCreateRequest(ctx, resourceGroupName, name, keyName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedHsmKeysClientListVersionsResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmKeysClientListVersionsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedHsmKeysClientListVersionsResponse{}, runtime.NewResponseError(resp) + } + return client.listVersionsHandleResponse(resp) + }, + }) +} + +// listVersionsCreateRequest creates the ListVersions request. +func (client *ManagedHsmKeysClient) listVersionsCreateRequest(ctx context.Context, resourceGroupName string, name string, keyName string, options *ManagedHsmKeysClientListVersionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/keys/{keyName}/versions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyName}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listVersionsHandleResponse handles the ListVersions response. +func (client *ManagedHsmKeysClient) listVersionsHandleResponse(resp *http.Response) (ManagedHsmKeysClientListVersionsResponse, error) { + result := ManagedHsmKeysClientListVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmKeyListResult); err != nil { + return ManagedHsmKeysClientListVersionsResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsms_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsms_client.go new file mode 100644 index 0000000000..e813142532 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/managedhsms_client.go @@ -0,0 +1,691 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// ManagedHsmsClient contains the methods for the ManagedHsms group. +// Don't use this type directly, use NewManagedHsmsClient() instead. +type ManagedHsmsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagedHsmsClient creates a new instance of ManagedHsmsClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewManagedHsmsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagedHsmsClient, error) { + cl, err := arm.NewClient(moduleName+".ManagedHsmsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagedHsmsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckMhsmNameAvailability - Checks that the managed hsm name is valid and is not already in use. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - mhsmName - The name of the managed hsm. +// - options - ManagedHsmsClientCheckMhsmNameAvailabilityOptions contains the optional parameters for the ManagedHsmsClient.CheckMhsmNameAvailability +// method. +func (client *ManagedHsmsClient) CheckMhsmNameAvailability(ctx context.Context, mhsmName CheckMhsmNameAvailabilityParameters, options *ManagedHsmsClientCheckMhsmNameAvailabilityOptions) (ManagedHsmsClientCheckMhsmNameAvailabilityResponse, error) { + var err error + req, err := client.checkMhsmNameAvailabilityCreateRequest(ctx, mhsmName, options) + if err != nil { + return ManagedHsmsClientCheckMhsmNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmsClientCheckMhsmNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedHsmsClientCheckMhsmNameAvailabilityResponse{}, err + } + resp, err := client.checkMhsmNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkMhsmNameAvailabilityCreateRequest creates the CheckMhsmNameAvailability request. +func (client *ManagedHsmsClient) checkMhsmNameAvailabilityCreateRequest(ctx context.Context, mhsmName CheckMhsmNameAvailabilityParameters, options *ManagedHsmsClientCheckMhsmNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/checkMhsmNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, mhsmName); err != nil { + return nil, err + } + return req, nil +} + +// checkMhsmNameAvailabilityHandleResponse handles the CheckMhsmNameAvailability response. +func (client *ManagedHsmsClient) checkMhsmNameAvailabilityHandleResponse(resp *http.Response) (ManagedHsmsClientCheckMhsmNameAvailabilityResponse, error) { + result := ManagedHsmsClientCheckMhsmNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckMhsmNameAvailabilityResult); err != nil { + return ManagedHsmsClientCheckMhsmNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdate - Create or update a managed HSM Pool in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - parameters - Parameters to create or update the managed HSM Pool +// - options - ManagedHsmsClientBeginCreateOrUpdateOptions contains the optional parameters for the ManagedHsmsClient.BeginCreateOrUpdate +// method. +func (client *ManagedHsmsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, name string, parameters ManagedHsm, options *ManagedHsmsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ManagedHsmsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[ManagedHsmsClientCreateOrUpdateResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[ManagedHsmsClientCreateOrUpdateResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// CreateOrUpdate - Create or update a managed HSM Pool in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ManagedHsmsClient) createOrUpdate(ctx context.Context, resourceGroupName string, name string, parameters ManagedHsm, options *ManagedHsmsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ManagedHsmsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, name string, parameters ManagedHsm, options *ManagedHsmsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified managed HSM Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - The name of the managed HSM Pool to delete +// - options - ManagedHsmsClientBeginDeleteOptions contains the optional parameters for the ManagedHsmsClient.BeginDelete method. +func (client *ManagedHsmsClient) BeginDelete(ctx context.Context, resourceGroupName string, name string, options *ManagedHsmsClientBeginDeleteOptions) (*runtime.Poller[ManagedHsmsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, name, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[ManagedHsmsClientDeleteResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[ManagedHsmsClientDeleteResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// Delete - Deletes the specified managed HSM Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ManagedHsmsClient) deleteOperation(ctx context.Context, resourceGroupName string, name string, options *ManagedHsmsClientBeginDeleteOptions) (*http.Response, error) { + var err error + req, err := client.deleteCreateRequest(ctx, resourceGroupName, name, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ManagedHsmsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, name string, options *ManagedHsmsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified managed HSM Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - The name of the managed HSM Pool. +// - options - ManagedHsmsClientGetOptions contains the optional parameters for the ManagedHsmsClient.Get method. +func (client *ManagedHsmsClient) Get(ctx context.Context, resourceGroupName string, name string, options *ManagedHsmsClientGetOptions) (ManagedHsmsClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, name, options) + if err != nil { + return ManagedHsmsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ManagedHsmsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagedHsmsClient) getCreateRequest(ctx context.Context, resourceGroupName string, name string, options *ManagedHsmsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagedHsmsClient) getHandleResponse(resp *http.Response) (ManagedHsmsClientGetResponse, error) { + result := ManagedHsmsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsm); err != nil { + return ManagedHsmsClientGetResponse{}, err + } + return result, nil +} + +// GetDeleted - Gets the specified deleted managed HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - name - The name of the deleted managed HSM. +// - location - The location of the deleted managed HSM. +// - options - ManagedHsmsClientGetDeletedOptions contains the optional parameters for the ManagedHsmsClient.GetDeleted method. +func (client *ManagedHsmsClient) GetDeleted(ctx context.Context, name string, location string, options *ManagedHsmsClientGetDeletedOptions) (ManagedHsmsClientGetDeletedResponse, error) { + var err error + req, err := client.getDeletedCreateRequest(ctx, name, location, options) + if err != nil { + return ManagedHsmsClientGetDeletedResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmsClientGetDeletedResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedHsmsClientGetDeletedResponse{}, err + } + resp, err := client.getDeletedHandleResponse(httpResp) + return resp, err +} + +// getDeletedCreateRequest creates the GetDeleted request. +func (client *ManagedHsmsClient) getDeletedCreateRequest(ctx context.Context, name string, location string, options *ManagedHsmsClientGetDeletedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedManagedHSMs/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDeletedHandleResponse handles the GetDeleted response. +func (client *ManagedHsmsClient) getDeletedHandleResponse(resp *http.Response) (ManagedHsmsClientGetDeletedResponse, error) { + result := ManagedHsmsClientGetDeletedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedManagedHsm); err != nil { + return ManagedHsmsClientGetDeletedResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - The List operation gets information about the managed HSM Pools associated with the subscription +// and within the specified resource group. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - options - ManagedHsmsClientListByResourceGroupOptions contains the optional parameters for the ManagedHsmsClient.NewListByResourceGroupPager +// method. +func (client *ManagedHsmsClient) NewListByResourceGroupPager(resourceGroupName string, options *ManagedHsmsClientListByResourceGroupOptions) *runtime.Pager[ManagedHsmsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedHsmsClientListByResourceGroupResponse]{ + More: func(page ManagedHsmsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedHsmsClientListByResourceGroupResponse) (ManagedHsmsClientListByResourceGroupResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedHsmsClientListByResourceGroupResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmsClientListByResourceGroupResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedHsmsClientListByResourceGroupResponse{}, runtime.NewResponseError(resp) + } + return client.listByResourceGroupHandleResponse(resp) + }, + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ManagedHsmsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ManagedHsmsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ManagedHsmsClient) listByResourceGroupHandleResponse(resp *http.Response) (ManagedHsmsClientListByResourceGroupResponse, error) { + result := ManagedHsmsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmListResult); err != nil { + return ManagedHsmsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - The List operation gets information about the managed HSM Pools associated with the subscription. +// +// Generated from API version 2023-07-01 +// - options - ManagedHsmsClientListBySubscriptionOptions contains the optional parameters for the ManagedHsmsClient.NewListBySubscriptionPager +// method. +func (client *ManagedHsmsClient) NewListBySubscriptionPager(options *ManagedHsmsClientListBySubscriptionOptions) *runtime.Pager[ManagedHsmsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedHsmsClientListBySubscriptionResponse]{ + More: func(page ManagedHsmsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedHsmsClientListBySubscriptionResponse) (ManagedHsmsClientListBySubscriptionResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listBySubscriptionCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedHsmsClientListBySubscriptionResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmsClientListBySubscriptionResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedHsmsClientListBySubscriptionResponse{}, runtime.NewResponseError(resp) + } + return client.listBySubscriptionHandleResponse(resp) + }, + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ManagedHsmsClient) listBySubscriptionCreateRequest(ctx context.Context, options *ManagedHsmsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/managedHSMs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ManagedHsmsClient) listBySubscriptionHandleResponse(resp *http.Response) (ManagedHsmsClientListBySubscriptionResponse, error) { + result := ManagedHsmsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedHsmListResult); err != nil { + return ManagedHsmsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewListDeletedPager - The List operation gets information about the deleted managed HSMs associated with the subscription. +// +// Generated from API version 2023-07-01 +// - options - ManagedHsmsClientListDeletedOptions contains the optional parameters for the ManagedHsmsClient.NewListDeletedPager +// method. +func (client *ManagedHsmsClient) NewListDeletedPager(options *ManagedHsmsClientListDeletedOptions) *runtime.Pager[ManagedHsmsClientListDeletedResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedHsmsClientListDeletedResponse]{ + More: func(page ManagedHsmsClientListDeletedResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedHsmsClientListDeletedResponse) (ManagedHsmsClientListDeletedResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listDeletedCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ManagedHsmsClientListDeletedResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedHsmsClientListDeletedResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagedHsmsClientListDeletedResponse{}, runtime.NewResponseError(resp) + } + return client.listDeletedHandleResponse(resp) + }, + }) +} + +// listDeletedCreateRequest creates the ListDeleted request. +func (client *ManagedHsmsClient) listDeletedCreateRequest(ctx context.Context, options *ManagedHsmsClientListDeletedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedManagedHSMs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listDeletedHandleResponse handles the ListDeleted response. +func (client *ManagedHsmsClient) listDeletedHandleResponse(resp *http.Response) (ManagedHsmsClientListDeletedResponse, error) { + result := ManagedHsmsClientListDeletedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedManagedHsmListResult); err != nil { + return ManagedHsmsClientListDeletedResponse{}, err + } + return result, nil +} + +// BeginPurgeDeleted - Permanently deletes the specified managed HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - name - The name of the soft-deleted managed HSM. +// - location - The location of the soft-deleted managed HSM. +// - options - ManagedHsmsClientBeginPurgeDeletedOptions contains the optional parameters for the ManagedHsmsClient.BeginPurgeDeleted +// method. +func (client *ManagedHsmsClient) BeginPurgeDeleted(ctx context.Context, name string, location string, options *ManagedHsmsClientBeginPurgeDeletedOptions) (*runtime.Poller[ManagedHsmsClientPurgeDeletedResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.purgeDeleted(ctx, name, location, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[ManagedHsmsClientPurgeDeletedResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[ManagedHsmsClientPurgeDeletedResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// PurgeDeleted - Permanently deletes the specified managed HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ManagedHsmsClient) purgeDeleted(ctx context.Context, name string, location string, options *ManagedHsmsClientBeginPurgeDeletedOptions) (*http.Response, error) { + var err error + req, err := client.purgeDeletedCreateRequest(ctx, name, location, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// purgeDeletedCreateRequest creates the PurgeDeleted request. +func (client *ManagedHsmsClient) purgeDeletedCreateRequest(ctx context.Context, name string, location string, options *ManagedHsmsClientBeginPurgeDeletedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedManagedHSMs/{name}/purge" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Update a managed HSM Pool in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - parameters - Parameters to patch the managed HSM Pool +// - options - ManagedHsmsClientBeginUpdateOptions contains the optional parameters for the ManagedHsmsClient.BeginUpdate method. +func (client *ManagedHsmsClient) BeginUpdate(ctx context.Context, resourceGroupName string, name string, parameters ManagedHsm, options *ManagedHsmsClientBeginUpdateOptions) (*runtime.Poller[ManagedHsmsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[ManagedHsmsClientUpdateResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[ManagedHsmsClientUpdateResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// Update - Update a managed HSM Pool in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *ManagedHsmsClient) update(ctx context.Context, resourceGroupName string, name string, parameters ManagedHsm, options *ManagedHsmsClientBeginUpdateOptions) (*http.Response, error) { + var err error + req, err := client.updateCreateRequest(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ManagedHsmsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, name string, parameters ManagedHsm, options *ManagedHsmsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivateendpointconnections_client.go new file mode 100644 index 0000000000..21550c25f2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivateendpointconnections_client.go @@ -0,0 +1,337 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// MHSMPrivateEndpointConnectionsClient contains the methods for the MHSMPrivateEndpointConnections group. +// Don't use this type directly, use NewMHSMPrivateEndpointConnectionsClient() instead. +type MHSMPrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMHSMPrivateEndpointConnectionsClient creates a new instance of MHSMPrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewMHSMPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MHSMPrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName+".MHSMPrivateEndpointConnectionsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MHSMPrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginDelete - Deletes the specified private endpoint connection associated with the managed hsm pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - privateEndpointConnectionName - Name of the private endpoint connection associated with the managed hsm pool. +// - options - MHSMPrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.BeginDelete +// method. +func (client *MHSMPrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, options *MHSMPrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[MHSMPrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, name, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[MHSMPrivateEndpointConnectionsClientDeleteResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[MHSMPrivateEndpointConnectionsClientDeleteResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// Delete - Deletes the specified private endpoint connection associated with the managed hsm pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *MHSMPrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, options *MHSMPrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + req, err := client.deleteCreateRequest(ctx, resourceGroupName, name, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *MHSMPrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, options *MHSMPrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified private endpoint connection associated with the managed HSM Pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - privateEndpointConnectionName - Name of the private endpoint connection associated with the managed hsm pool. +// - options - MHSMPrivateEndpointConnectionsClientGetOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.Get +// method. +func (client *MHSMPrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, options *MHSMPrivateEndpointConnectionsClientGetOptions) (MHSMPrivateEndpointConnectionsClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, name, privateEndpointConnectionName, options) + if err != nil { + return MHSMPrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MHSMPrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MHSMPrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *MHSMPrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, options *MHSMPrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *MHSMPrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (MHSMPrivateEndpointConnectionsClientGetResponse, error) { + result := MHSMPrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MHSMPrivateEndpointConnection); err != nil { + return MHSMPrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourcePager - The List operation gets information about the private endpoint connections associated with the +// managed HSM Pool. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - options - MHSMPrivateEndpointConnectionsClientListByResourceOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.NewListByResourcePager +// method. +func (client *MHSMPrivateEndpointConnectionsClient) NewListByResourcePager(resourceGroupName string, name string, options *MHSMPrivateEndpointConnectionsClientListByResourceOptions) *runtime.Pager[MHSMPrivateEndpointConnectionsClientListByResourceResponse] { + return runtime.NewPager(runtime.PagingHandler[MHSMPrivateEndpointConnectionsClientListByResourceResponse]{ + More: func(page MHSMPrivateEndpointConnectionsClientListByResourceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MHSMPrivateEndpointConnectionsClientListByResourceResponse) (MHSMPrivateEndpointConnectionsClientListByResourceResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listByResourceCreateRequest(ctx, resourceGroupName, name, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return MHSMPrivateEndpointConnectionsClientListByResourceResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MHSMPrivateEndpointConnectionsClientListByResourceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return MHSMPrivateEndpointConnectionsClientListByResourceResponse{}, runtime.NewResponseError(resp) + } + return client.listByResourceHandleResponse(resp) + }, + }) +} + +// listByResourceCreateRequest creates the ListByResource request. +func (client *MHSMPrivateEndpointConnectionsClient) listByResourceCreateRequest(ctx context.Context, resourceGroupName string, name string, options *MHSMPrivateEndpointConnectionsClientListByResourceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceHandleResponse handles the ListByResource response. +func (client *MHSMPrivateEndpointConnectionsClient) listByResourceHandleResponse(resp *http.Response) (MHSMPrivateEndpointConnectionsClientListByResourceResponse, error) { + result := MHSMPrivateEndpointConnectionsClientListByResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MHSMPrivateEndpointConnectionsListResult); err != nil { + return MHSMPrivateEndpointConnectionsClientListByResourceResponse{}, err + } + return result, nil +} + +// Put - Updates the specified private endpoint connection associated with the managed hsm pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - privateEndpointConnectionName - Name of the private endpoint connection associated with the managed hsm pool. +// - properties - The intended state of private endpoint connection. +// - options - MHSMPrivateEndpointConnectionsClientPutOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.Put +// method. +func (client *MHSMPrivateEndpointConnectionsClient) Put(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, properties MHSMPrivateEndpointConnection, options *MHSMPrivateEndpointConnectionsClientPutOptions) (MHSMPrivateEndpointConnectionsClientPutResponse, error) { + var err error + req, err := client.putCreateRequest(ctx, resourceGroupName, name, privateEndpointConnectionName, properties, options) + if err != nil { + return MHSMPrivateEndpointConnectionsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MHSMPrivateEndpointConnectionsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MHSMPrivateEndpointConnectionsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *MHSMPrivateEndpointConnectionsClient) putCreateRequest(ctx context.Context, resourceGroupName string, name string, privateEndpointConnectionName string, properties MHSMPrivateEndpointConnection, options *MHSMPrivateEndpointConnectionsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *MHSMPrivateEndpointConnectionsClient) putHandleResponse(resp *http.Response) (MHSMPrivateEndpointConnectionsClientPutResponse, error) { + result := MHSMPrivateEndpointConnectionsClientPutResponse{} + if val := resp.Header.Get("Azure-AsyncOperation"); val != "" { + result.AzureAsyncOperation = &val + } + if val := resp.Header.Get("Retry-After"); val != "" { + retryAfter32, err := strconv.ParseInt(val, 10, 32) + retryAfter := int32(retryAfter32) + if err != nil { + return MHSMPrivateEndpointConnectionsClientPutResponse{}, err + } + result.RetryAfter = &retryAfter + } + if err := runtime.UnmarshalAsJSON(resp, &result.MHSMPrivateEndpointConnection); err != nil { + return MHSMPrivateEndpointConnectionsClientPutResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivatelinkresources_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivatelinkresources_client.go new file mode 100644 index 0000000000..3370d1b054 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmprivatelinkresources_client.go @@ -0,0 +1,106 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MHSMPrivateLinkResourcesClient contains the methods for the MHSMPrivateLinkResources group. +// Don't use this type directly, use NewMHSMPrivateLinkResourcesClient() instead. +type MHSMPrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMHSMPrivateLinkResourcesClient creates a new instance of MHSMPrivateLinkResourcesClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewMHSMPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MHSMPrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName+".MHSMPrivateLinkResourcesClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MHSMPrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// ListByMHSMResource - Gets the private link resources supported for the managed hsm pool. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - options - MHSMPrivateLinkResourcesClientListByMHSMResourceOptions contains the optional parameters for the MHSMPrivateLinkResourcesClient.ListByMHSMResource +// method. +func (client *MHSMPrivateLinkResourcesClient) ListByMHSMResource(ctx context.Context, resourceGroupName string, name string, options *MHSMPrivateLinkResourcesClientListByMHSMResourceOptions) (MHSMPrivateLinkResourcesClientListByMHSMResourceResponse, error) { + var err error + req, err := client.listByMHSMResourceCreateRequest(ctx, resourceGroupName, name, options) + if err != nil { + return MHSMPrivateLinkResourcesClientListByMHSMResourceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MHSMPrivateLinkResourcesClientListByMHSMResourceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MHSMPrivateLinkResourcesClientListByMHSMResourceResponse{}, err + } + resp, err := client.listByMHSMResourceHandleResponse(httpResp) + return resp, err +} + +// listByMHSMResourceCreateRequest creates the ListByMHSMResource request. +func (client *MHSMPrivateLinkResourcesClient) listByMHSMResourceCreateRequest(ctx context.Context, resourceGroupName string, name string, options *MHSMPrivateLinkResourcesClientListByMHSMResourceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByMHSMResourceHandleResponse handles the ListByMHSMResource response. +func (client *MHSMPrivateLinkResourcesClient) listByMHSMResourceHandleResponse(resp *http.Response) (MHSMPrivateLinkResourcesClientListByMHSMResourceResponse, error) { + result := MHSMPrivateLinkResourcesClientListByMHSMResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MHSMPrivateLinkResourceListResult); err != nil { + return MHSMPrivateLinkResourcesClientListByMHSMResourceResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmregions_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmregions_client.go new file mode 100644 index 0000000000..f3f2f125ca --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/mhsmregions_client.go @@ -0,0 +1,115 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MHSMRegionsClient contains the methods for the MHSMRegions group. +// Don't use this type directly, use NewMHSMRegionsClient() instead. +type MHSMRegionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMHSMRegionsClient creates a new instance of MHSMRegionsClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewMHSMRegionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MHSMRegionsClient, error) { + cl, err := arm.NewClient(moduleName+".MHSMRegionsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MHSMRegionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByResourcePager - The List operation gets information about the regions associated with the managed HSM Pool. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the managed HSM pool. +// - name - Name of the managed HSM Pool +// - options - MHSMRegionsClientListByResourceOptions contains the optional parameters for the MHSMRegionsClient.NewListByResourcePager +// method. +func (client *MHSMRegionsClient) NewListByResourcePager(resourceGroupName string, name string, options *MHSMRegionsClientListByResourceOptions) *runtime.Pager[MHSMRegionsClientListByResourceResponse] { + return runtime.NewPager(runtime.PagingHandler[MHSMRegionsClientListByResourceResponse]{ + More: func(page MHSMRegionsClientListByResourceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MHSMRegionsClientListByResourceResponse) (MHSMRegionsClientListByResourceResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listByResourceCreateRequest(ctx, resourceGroupName, name, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return MHSMRegionsClientListByResourceResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MHSMRegionsClientListByResourceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return MHSMRegionsClientListByResourceResponse{}, runtime.NewResponseError(resp) + } + return client.listByResourceHandleResponse(resp) + }, + }) +} + +// listByResourceCreateRequest creates the ListByResource request. +func (client *MHSMRegionsClient) listByResourceCreateRequest(ctx context.Context, resourceGroupName string, name string, options *MHSMRegionsClientListByResourceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/regions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceHandleResponse handles the ListByResource response. +func (client *MHSMRegionsClient) listByResourceHandleResponse(resp *http.Response) (MHSMRegionsClientListByResourceResponse, error) { + result := MHSMRegionsClientListByResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MHSMRegionsListResult); err != nil { + return MHSMRegionsClientListByResourceResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models.go new file mode 100644 index 0000000000..edf63b4371 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models.go @@ -0,0 +1,1402 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import "time" + +// AccessPolicyEntry - An identity that have access to the key vault. All identities in the array must use the same tenant +// ID as the key vault's tenant ID. +type AccessPolicyEntry struct { + // REQUIRED; The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. + // The object ID must be unique for the list of access policies. + ObjectID *string + + // REQUIRED; Permissions the identity has for keys, secrets and certificates. + Permissions *Permissions + + // REQUIRED; The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + TenantID *string + + // Application ID of the client making request on behalf of a principal + ApplicationID *string +} + +type Action struct { + // The type of action. + Type *KeyRotationPolicyActionType +} + +// CheckMhsmNameAvailabilityParameters - The parameters used to check the availability of the managed hsm name. +type CheckMhsmNameAvailabilityParameters struct { + // REQUIRED; The managed hsm name. + Name *string +} + +// CheckMhsmNameAvailabilityResult - The CheckMhsmNameAvailability operation response. +type CheckMhsmNameAvailabilityResult struct { + // READ-ONLY; An error message explaining the Reason value in more detail. + Message *string + + // READ-ONLY; A boolean value that indicates whether the name is available for you to use. If true, the name is available. + // If false, the name has already been taken or is invalid and cannot be used. + NameAvailable *bool + + // READ-ONLY; The reason that a managed hsm name could not be used. The reason element is only returned if NameAvailable is + // false. + Reason *Reason +} + +// CheckNameAvailabilityResult - The CheckNameAvailability operation response. +type CheckNameAvailabilityResult struct { + // READ-ONLY; An error message explaining the Reason value in more detail. + Message *string + + // READ-ONLY; A boolean value that indicates whether the name is available for you to use. If true, the name is available. + // If false, the name has already been taken or is invalid and cannot be used. + NameAvailable *bool + + // READ-ONLY; The reason that a vault name could not be used. The Reason element is only returned if NameAvailable is false. + Reason *Reason +} + +type DeletedManagedHsm struct { + // Properties of the deleted managed HSM + Properties *DeletedManagedHsmProperties + + // READ-ONLY; The Azure Resource Manager resource ID for the deleted managed HSM Pool. + ID *string + + // READ-ONLY; The name of the managed HSM Pool. + Name *string + + // READ-ONLY; The resource type of the managed HSM Pool. + Type *string +} + +// DeletedManagedHsmListResult - List of deleted managed HSM Pools +type DeletedManagedHsmListResult struct { + // The URL to get the next set of deleted managed HSM Pools. + NextLink *string + + // The list of deleted managed HSM Pools. + Value []*DeletedManagedHsm +} + +// DeletedManagedHsmProperties - Properties of the deleted managed HSM. +type DeletedManagedHsmProperties struct { + // READ-ONLY; The deleted date. + DeletionDate *time.Time + + // READ-ONLY; The location of the original managed HSM. + Location *string + + // READ-ONLY; The resource id of the original managed HSM. + MhsmID *string + + // READ-ONLY; Purge protection status of the original managed HSM. + PurgeProtectionEnabled *bool + + // READ-ONLY; The scheduled purged date. + ScheduledPurgeDate *time.Time + + // READ-ONLY; Tags of the original managed HSM. + Tags map[string]*string +} + +// DeletedVault - Deleted vault information with extended details. +type DeletedVault struct { + // Properties of the vault + Properties *DeletedVaultProperties + + // READ-ONLY; The resource ID for the deleted key vault. + ID *string + + // READ-ONLY; The name of the key vault. + Name *string + + // READ-ONLY; The resource type of the key vault. + Type *string +} + +// DeletedVaultListResult - List of vaults +type DeletedVaultListResult struct { + // The URL to get the next set of deleted vaults. + NextLink *string + + // The list of deleted vaults. + Value []*DeletedVault +} + +// DeletedVaultProperties - Properties of the deleted vault. +type DeletedVaultProperties struct { + // READ-ONLY; The deleted date. + DeletionDate *time.Time + + // READ-ONLY; The location of the original vault. + Location *string + + // READ-ONLY; Purge protection status of the original vault. + PurgeProtectionEnabled *bool + + // READ-ONLY; The scheduled purged date. + ScheduledPurgeDate *time.Time + + // READ-ONLY; Tags of the original vault. + Tags map[string]*string + + // READ-ONLY; The resource id of the original vault. + VaultID *string +} + +// DimensionProperties - Type of operation: get, read, delete, etc. +type DimensionProperties struct { + // Display name of dimension. + DisplayName *string + + // Name of dimension. + Name *string + + // Property to specify whether the dimension should be exported for Shoebox. + ToBeExportedForShoebox *bool +} + +// IPRule - A rule governing the accessibility of a vault from a specific ip address or ip range. +type IPRule struct { + // REQUIRED; An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses + // that start with 124.56.78). + Value *string +} + +// Key - The key resource. +type Key struct { + // REQUIRED; The properties of the key. + Properties *KeyProperties + + // READ-ONLY; Fully qualified identifier of the key vault resource. + ID *string + + // READ-ONLY; Azure location of the key vault resource. + Location *string + + // READ-ONLY; Name of the key vault resource. + Name *string + + // READ-ONLY; Tags assigned to the key vault resource. + Tags map[string]*string + + // READ-ONLY; Resource type of the key vault resource. + Type *string +} + +// KeyAttributes - The object attributes managed by the Azure Key Vault service. +type KeyAttributes struct { + // Determines whether or not the object is enabled. + Enabled *bool + + // Expiry date in seconds since 1970-01-01T00:00:00Z. + Expires *int64 + + // Indicates if the private key can be exported. + Exportable *bool + + // Not before date in seconds since 1970-01-01T00:00:00Z. + NotBefore *int64 + + // READ-ONLY; Creation time in seconds since 1970-01-01T00:00:00Z. + Created *int64 + + // READ-ONLY; The deletion recovery level currently in effect for the object. If it contains 'Purgeable', then the object + // can be permanently deleted by a privileged user; otherwise, only the system can purge the + // object at the end of the retention interval. + RecoveryLevel *DeletionRecoveryLevel + + // READ-ONLY; Last updated time in seconds since 1970-01-01T00:00:00Z. + Updated *int64 +} + +// KeyCreateParameters - The parameters used to create a key. +type KeyCreateParameters struct { + // REQUIRED; The properties of the key to be created. + Properties *KeyProperties + + // The tags that will be assigned to the key. + Tags map[string]*string +} + +// KeyListResult - The page of keys. +type KeyListResult struct { + // The URL to get the next page of keys. + NextLink *string + + // The key resources. + Value []*Key +} + +// KeyProperties - The properties of the key. +type KeyProperties struct { + // The attributes of the key. + Attributes *KeyAttributes + + // The elliptic curve name. For valid values, see JsonWebKeyCurveName. + CurveName *JSONWebKeyCurveName + KeyOps []*JSONWebKeyOperation + + // The key size in bits. For example: 2048, 3072, or 4096 for RSA. + KeySize *int32 + + // The type of the key. For valid values, see JsonWebKeyType. + Kty *JSONWebKeyType + + // Key release policy in response. It will be used for both output and input. Omitted if empty + ReleasePolicy *KeyReleasePolicy + + // Key rotation policy in response. It will be used for both output and input. Omitted if empty + RotationPolicy *RotationPolicy + + // READ-ONLY; The URI to retrieve the current version of the key. + KeyURI *string + + // READ-ONLY; The URI to retrieve the specific version of the key. + KeyURIWithVersion *string +} + +type KeyReleasePolicy struct { + // Content type and version of key release policy + ContentType *string + + // Blob encoding the policy rules under which the key can be released. + Data []byte +} + +type KeyRotationPolicyAttributes struct { + // The expiration time for the new key version. It should be in ISO8601 format. Eg: 'P90D', 'P1Y'. + ExpiryTime *string + + // READ-ONLY; Creation time in seconds since 1970-01-01T00:00:00Z. + Created *int64 + + // READ-ONLY; Last updated time in seconds since 1970-01-01T00:00:00Z. + Updated *int64 +} + +type LifetimeAction struct { + // The action of key rotation policy lifetimeAction. + Action *Action + + // The trigger of key rotation policy lifetimeAction. + Trigger *Trigger +} + +// LogSpecification - Log specification of operation. +type LogSpecification struct { + // Blob duration of specification. + BlobDuration *string + + // Display name of log specification. + DisplayName *string + + // Name of log specification. + Name *string +} + +// MHSMGeoReplicatedRegion - A region that this managed HSM Pool has been extended to. +type MHSMGeoReplicatedRegion struct { + // A boolean value that indicates whether the region is the primary region or a secondary region. + IsPrimary *bool + + // Name of the geo replicated region. + Name *string + + // READ-ONLY; Provisioning state of the geo replicated region. + ProvisioningState *GeoReplicationRegionProvisioningState +} + +// MHSMIPRule - A rule governing the accessibility of a managed HSM pool from a specific IP address or IP range. +type MHSMIPRule struct { + // REQUIRED; An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses + // that start with 124.56.78). + Value *string +} + +// MHSMNetworkRuleSet - A set of rules governing the network accessibility of a managed hsm pool. +type MHSMNetworkRuleSet struct { + // Tells what traffic can bypass network rules. This can be 'AzureServices' or 'None'. If not specified the default is 'AzureServices'. + Bypass *NetworkRuleBypassOptions + + // The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property + // has been evaluated. + DefaultAction *NetworkRuleAction + + // The list of IP address rules. + IPRules []*MHSMIPRule + + // The list of virtual network rules. + VirtualNetworkRules []*MHSMVirtualNetworkRule +} + +// MHSMPrivateEndpoint - Private endpoint object properties. +type MHSMPrivateEndpoint struct { + // READ-ONLY; Full identifier of the private endpoint resource. + ID *string +} + +// MHSMPrivateEndpointConnection - Private endpoint connection resource. +type MHSMPrivateEndpointConnection struct { + // Modified whenever there is a change in the state of private endpoint connection. + Etag *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // The supported Azure location where the managed HSM Pool should be created. + Location *string + + // Resource properties. + Properties *MHSMPrivateEndpointConnectionProperties + + // SKU details + SKU *ManagedHsmSKU + + // Resource tags + Tags map[string]*string + + // READ-ONLY; The Azure Resource Manager resource ID for the managed HSM Pool. + ID *string + + // READ-ONLY; The name of the managed HSM Pool. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the key vault resource. + SystemData *SystemData + + // READ-ONLY; The resource type of the managed HSM Pool. + Type *string +} + +// MHSMPrivateEndpointConnectionItem - Private endpoint connection item. +type MHSMPrivateEndpointConnectionItem struct { + // Modified whenever there is a change in the state of private endpoint connection. + Etag *string + + // Id of private endpoint connection. + ID *string + + // Private endpoint connection properties. + Properties *MHSMPrivateEndpointConnectionProperties +} + +// MHSMPrivateEndpointConnectionProperties - Properties of the private endpoint connection resource. +type MHSMPrivateEndpointConnectionProperties struct { + // Properties of the private endpoint object. + PrivateEndpoint *MHSMPrivateEndpoint + + // Approval state of the private link connection. + PrivateLinkServiceConnectionState *MHSMPrivateLinkServiceConnectionState + + // Provisioning state of the private endpoint connection. + ProvisioningState *PrivateEndpointConnectionProvisioningState +} + +// MHSMPrivateEndpointConnectionsListResult - List of private endpoint connections associated with a managed HSM Pools +type MHSMPrivateEndpointConnectionsListResult struct { + // The URL to get the next set of managed HSM Pools. + NextLink *string + + // The private endpoint connection associated with a managed HSM Pools. + Value []*MHSMPrivateEndpointConnection +} + +// MHSMPrivateLinkResource - A private link resource +type MHSMPrivateLinkResource struct { + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // The supported Azure location where the managed HSM Pool should be created. + Location *string + + // Resource properties. + Properties *MHSMPrivateLinkResourceProperties + + // SKU details + SKU *ManagedHsmSKU + + // Resource tags + Tags map[string]*string + + // READ-ONLY; The Azure Resource Manager resource ID for the managed HSM Pool. + ID *string + + // READ-ONLY; The name of the managed HSM Pool. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the key vault resource. + SystemData *SystemData + + // READ-ONLY; The resource type of the managed HSM Pool. + Type *string +} + +// MHSMPrivateLinkResourceListResult - A list of private link resources +type MHSMPrivateLinkResourceListResult struct { + // Array of private link resources + Value []*MHSMPrivateLinkResource +} + +// MHSMPrivateLinkResourceProperties - Properties of a private link resource. +type MHSMPrivateLinkResourceProperties struct { + // Required DNS zone names of the the private link resource. + RequiredZoneNames []*string + + // READ-ONLY; Group identifier of private link resource. + GroupID *string + + // READ-ONLY; Required member names of private link resource. + RequiredMembers []*string +} + +// MHSMPrivateLinkServiceConnectionState - An object that represents the approval state of the private link connection. +type MHSMPrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *ActionsRequired + + // The reason for approval or rejection. + Description *string + + // Indicates whether the connection has been approved, rejected or removed by the key vault owner. + Status *PrivateEndpointServiceConnectionStatus +} + +// MHSMRegionsListResult - List of regions associated with a managed HSM Pools +type MHSMRegionsListResult struct { + // The URL to get the next set of managed HSM Pools. + NextLink *string + + // The region associated with a managed HSM Pools. + Value []*MHSMGeoReplicatedRegion +} + +// MHSMVirtualNetworkRule - A rule governing the accessibility of a managed hsm pool from a specific virtual network. +type MHSMVirtualNetworkRule struct { + // REQUIRED; Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. + ID *string +} + +// ManagedHSMSecurityDomainProperties - The security domain properties of the managed hsm. +type ManagedHSMSecurityDomainProperties struct { + // READ-ONLY; Activation Status + ActivationStatus *ActivationStatus + + // READ-ONLY; Activation Status Message. + ActivationStatusMessage *string +} + +// ManagedHsm - Resource information with extended details. +type ManagedHsm struct { + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // The supported Azure location where the managed HSM Pool should be created. + Location *string + + // Properties of the managed HSM + Properties *ManagedHsmProperties + + // SKU details + SKU *ManagedHsmSKU + + // Resource tags + Tags map[string]*string + + // READ-ONLY; The Azure Resource Manager resource ID for the managed HSM Pool. + ID *string + + // READ-ONLY; The name of the managed HSM Pool. + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the key vault resource. + SystemData *SystemData + + // READ-ONLY; The resource type of the managed HSM Pool. + Type *string +} + +type ManagedHsmAction struct { + // The type of action. + Type *KeyRotationPolicyActionType +} + +// ManagedHsmKey - The key resource. +type ManagedHsmKey struct { + // REQUIRED; The properties of the key. + Properties *ManagedHsmKeyProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ManagedHsmKeyAttributes - The object attributes managed by the Azure Key Vault service. +type ManagedHsmKeyAttributes struct { + // Determines whether or not the object is enabled. + Enabled *bool + + // Expiry date in seconds since 1970-01-01T00:00:00Z. + Expires *int64 + + // Indicates if the private key can be exported. + Exportable *bool + + // Not before date in seconds since 1970-01-01T00:00:00Z. + NotBefore *int64 + + // READ-ONLY; Creation time in seconds since 1970-01-01T00:00:00Z. + Created *int64 + + // READ-ONLY; The deletion recovery level currently in effect for the object. If it contains 'Purgeable', then the object + // can be permanently deleted by a privileged user; otherwise, only the system can purge the + // object at the end of the retention interval. + RecoveryLevel *DeletionRecoveryLevel + + // READ-ONLY; Last updated time in seconds since 1970-01-01T00:00:00Z. + Updated *int64 +} + +// ManagedHsmKeyCreateParameters - The parameters used to create a key. +type ManagedHsmKeyCreateParameters struct { + // REQUIRED; The properties of the key to be created. + Properties *ManagedHsmKeyProperties + + // The tags that will be assigned to the key. + Tags map[string]*string +} + +// ManagedHsmKeyListResult - The page of keys. +type ManagedHsmKeyListResult struct { + // The URL to get the next page of keys. + NextLink *string + + // The key resources. + Value []*ManagedHsmKey +} + +// ManagedHsmKeyProperties - The properties of the key. +type ManagedHsmKeyProperties struct { + // The attributes of the key. + Attributes *ManagedHsmKeyAttributes + + // The elliptic curve name. For valid values, see JsonWebKeyCurveName. + CurveName *JSONWebKeyCurveName + KeyOps []*JSONWebKeyOperation + + // The key size in bits. For example: 2048, 3072, or 4096 for RSA. + KeySize *int32 + + // The type of the key. For valid values, see JsonWebKeyType. + Kty *JSONWebKeyType + + // Key release policy in response. It will be used for both output and input. Omitted if empty + ReleasePolicy *ManagedHsmKeyReleasePolicy + + // Key rotation policy in response. It will be used for both output and input. Omitted if empty + RotationPolicy *ManagedHsmRotationPolicy + + // READ-ONLY; The URI to retrieve the current version of the key. + KeyURI *string + + // READ-ONLY; The URI to retrieve the specific version of the key. + KeyURIWithVersion *string +} + +type ManagedHsmKeyReleasePolicy struct { + // Content type and version of key release policy + ContentType *string + + // Blob encoding the policy rules under which the key can be released. + Data []byte +} + +type ManagedHsmKeyRotationPolicyAttributes struct { + // The expiration time for the new key version. It should be in ISO8601 format. Eg: 'P90D', 'P1Y'. + ExpiryTime *string + + // READ-ONLY; Creation time in seconds since 1970-01-01T00:00:00Z. + Created *int64 + + // READ-ONLY; Last updated time in seconds since 1970-01-01T00:00:00Z. + Updated *int64 +} + +type ManagedHsmLifetimeAction struct { + // The action of key rotation policy lifetimeAction. + Action *ManagedHsmAction + + // The trigger of key rotation policy lifetimeAction. + Trigger *ManagedHsmTrigger +} + +// ManagedHsmListResult - List of managed HSM Pools +type ManagedHsmListResult struct { + // The URL to get the next set of managed HSM Pools. + NextLink *string + + // The list of managed HSM Pools. + Value []*ManagedHsm +} + +// ManagedHsmProperties - Properties of the managed HSM Pool +type ManagedHsmProperties struct { + // The create mode to indicate whether the resource is being created or is being recovered from a deleted resource. + CreateMode *CreateMode + + // Property specifying whether protection against purge is enabled for this managed HSM pool. Setting this property to true + // activates protection against purge for this managed HSM pool and its content - + // only the Managed HSM service may initiate a hard, irrecoverable deletion. Enabling this functionality is irreversible. + EnablePurgeProtection *bool + + // Property to specify whether the 'soft delete' functionality is enabled for this managed HSM pool. Soft delete is enabled + // by default for all managed HSMs and is immutable. + EnableSoftDelete *bool + + // Array of initial administrators object ids for this managed hsm pool. + InitialAdminObjectIDs []*string + + // Rules governing the accessibility of the key vault from specific network locations. + NetworkACLs *MHSMNetworkRuleSet + + // Control permission to the managed HSM from public networks. + PublicNetworkAccess *PublicNetworkAccess + + // List of all regions associated with the managed hsm pool. + Regions []*MHSMGeoReplicatedRegion + + // Soft deleted data retention days. When you delete an HSM or a key, it will remain recoverable for the configured retention + // period or for a default period of 90 days. It accepts values between 7 and + // 90. + SoftDeleteRetentionInDays *int32 + + // The Azure Active Directory tenant ID that should be used for authenticating requests to the managed HSM pool. + TenantID *string + + // READ-ONLY; The URI of the managed hsm pool for performing operations on keys. + HsmURI *string + + // READ-ONLY; List of private endpoint connections associated with the managed hsm pool. + PrivateEndpointConnections []*MHSMPrivateEndpointConnectionItem + + // READ-ONLY; Provisioning state. + ProvisioningState *ProvisioningState + + // READ-ONLY; The scheduled purge date in UTC. + ScheduledPurgeDate *time.Time + + // READ-ONLY; Managed HSM security domain properties. + SecurityDomainProperties *ManagedHSMSecurityDomainProperties + + // READ-ONLY; Resource Status Message. + StatusMessage *string +} + +type ManagedHsmRotationPolicy struct { + // The attributes of key rotation policy. + Attributes *ManagedHsmKeyRotationPolicyAttributes + + // The lifetimeActions for key rotation action. + LifetimeActions []*ManagedHsmLifetimeAction +} + +// ManagedHsmSKU - SKU details +type ManagedHsmSKU struct { + // REQUIRED; SKU Family of the managed HSM Pool + Family *ManagedHsmSKUFamily + + // REQUIRED; SKU of the managed HSM Pool + Name *ManagedHsmSKUName +} + +type ManagedHsmTrigger struct { + // The time duration after key creation to rotate the key. It only applies to rotate. It will be in ISO 8601 duration format. + // Eg: 'P90D', 'P1Y'. + TimeAfterCreate *string + + // The time duration before key expiring to rotate or notify. It will be in ISO 8601 duration format. Eg: 'P90D', 'P1Y'. + TimeBeforeExpiry *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + Type *ManagedServiceIdentityType + + // The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM + // resource ids in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + // The dictionary values can be empty objects ({}) in + // requests. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// MetricSpecification - Metric specification of operation. +type MetricSpecification struct { + // The metric aggregation type. Possible values include: 'Average', 'Count', 'Total'. + AggregationType *string + + // The dimensions of metric + Dimensions []*DimensionProperties + + // Display description of metric specification. + DisplayDescription *string + + // Display name of metric specification. + DisplayName *string + + // Property to specify whether to fill gap with zero. + FillGapWithZero *bool + + // The internal metric name. + InternalMetricName *string + + // The metric lock aggregation type. + LockAggregationType *string + + // Name of metric specification. + Name *string + + // The supported aggregation types for the metrics. + SupportedAggregationTypes []*string + + // The supported time grain types for the metrics. + SupportedTimeGrainTypes []*string + + // The metric unit. Possible values include: 'Bytes', 'Count', 'Milliseconds'. + Unit *string +} + +// NetworkRuleSet - A set of rules governing the network accessibility of a vault. +type NetworkRuleSet struct { + // Tells what traffic can bypass network rules. This can be 'AzureServices' or 'None'. If not specified the default is 'AzureServices'. + Bypass *NetworkRuleBypassOptions + + // The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property + // has been evaluated. + DefaultAction *NetworkRuleAction + + // The list of IP address rules. + IPRules []*IPRule + + // The list of virtual network rules. + VirtualNetworkRules []*VirtualNetworkRule +} + +// Operation - Key Vault REST API operation definition. +type Operation struct { + // Display metadata associated with the operation. + Display *OperationDisplay + + // Property to specify whether the action is a data action. + IsDataAction *bool + + // Operation name: {provider}/{resource}/{operation} + Name *string + + // Properties of operation, include metric specifications. + OperationProperties *OperationProperties + + // The origin of operations. + Origin *string +} + +// OperationDisplay - Display metadata associated with the operation. +type OperationDisplay struct { + // Description of operation. + Description *string + + // Type of operation: get, read, delete, etc. + Operation *string + + // Service provider: Microsoft Key Vault. + Provider *string + + // Resource on which the operation is performed etc. + Resource *string +} + +// OperationListResult - Result of the request to list Storage operations. It contains a list of operations and a URL link +// to get the next set of results. +type OperationListResult struct { + // The URL to get the next set of operations. + NextLink *string + + // List of Storage operations supported by the Storage resource provider. + Value []*Operation +} + +// OperationProperties - Properties of operation, include metric specifications. +type OperationProperties struct { + // One property of operation, include metric specifications. + ServiceSpecification *ServiceSpecification +} + +// Permissions the identity has for keys, secrets, certificates and storage. +type Permissions struct { + // Permissions to certificates + Certificates []*CertificatePermissions + + // Permissions to keys + Keys []*KeyPermissions + + // Permissions to secrets + Secrets []*SecretPermissions + + // Permissions to storage accounts + Storage []*StoragePermissions +} + +// PrivateEndpoint - Private endpoint object properties. +type PrivateEndpoint struct { + // READ-ONLY; Full identifier of the private endpoint resource. + ID *string +} + +// PrivateEndpointConnection - Private endpoint connection resource. +type PrivateEndpointConnection struct { + // Modified whenever there is a change in the state of private endpoint connection. + Etag *string + + // Resource properties. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; Fully qualified identifier of the key vault resource. + ID *string + + // READ-ONLY; Azure location of the key vault resource. + Location *string + + // READ-ONLY; Name of the key vault resource. + Name *string + + // READ-ONLY; Tags assigned to the key vault resource. + Tags map[string]*string + + // READ-ONLY; Resource type of the key vault resource. + Type *string +} + +// PrivateEndpointConnectionItem - Private endpoint connection item. +type PrivateEndpointConnectionItem struct { + // Modified whenever there is a change in the state of private endpoint connection. + Etag *string + + // Id of private endpoint connection. + ID *string + + // Private endpoint connection properties. + Properties *PrivateEndpointConnectionProperties +} + +// PrivateEndpointConnectionListResult - List of private endpoint connections. +type PrivateEndpointConnectionListResult struct { + // The URL to get the next set of private endpoint connections. + NextLink *string + + // The list of private endpoint connections. + Value []*PrivateEndpointConnection +} + +// PrivateEndpointConnectionProperties - Properties of the private endpoint connection resource. +type PrivateEndpointConnectionProperties struct { + // Properties of the private endpoint object. + PrivateEndpoint *PrivateEndpoint + + // Approval state of the private link connection. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // Provisioning state of the private endpoint connection. + ProvisioningState *PrivateEndpointConnectionProvisioningState +} + +// PrivateLinkResource - A private link resource +type PrivateLinkResource struct { + // Resource properties. + Properties *PrivateLinkResourceProperties + + // READ-ONLY; Fully qualified identifier of the key vault resource. + ID *string + + // READ-ONLY; Azure location of the key vault resource. + Location *string + + // READ-ONLY; Name of the key vault resource. + Name *string + + // READ-ONLY; Tags assigned to the key vault resource. + Tags map[string]*string + + // READ-ONLY; Resource type of the key vault resource. + Type *string +} + +// PrivateLinkResourceListResult - A list of private link resources +type PrivateLinkResourceListResult struct { + // Array of private link resources + Value []*PrivateLinkResource +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // Required DNS zone names of the the private link resource. + RequiredZoneNames []*string + + // READ-ONLY; Group identifier of private link resource. + GroupID *string + + // READ-ONLY; Required member names of private link resource. + RequiredMembers []*string +} + +// PrivateLinkServiceConnectionState - An object that represents the approval state of the private link connection. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *ActionsRequired + + // The reason for approval or rejection. + Description *string + + // Indicates whether the connection has been approved, rejected or removed by the key vault owner. + Status *PrivateEndpointServiceConnectionStatus +} + +// Resource - Key Vault resource +type Resource struct { + // READ-ONLY; Fully qualified identifier of the key vault resource. + ID *string + + // READ-ONLY; Azure location of the key vault resource. + Location *string + + // READ-ONLY; Name of the key vault resource. + Name *string + + // READ-ONLY; Tags assigned to the key vault resource. + Tags map[string]*string + + // READ-ONLY; Resource type of the key vault resource. + Type *string +} + +// ResourceListResult - List of vault resources. +type ResourceListResult struct { + // The URL to get the next set of vault resources. + NextLink *string + + // The list of vault resources. + Value []*Resource +} + +type RotationPolicy struct { + // The attributes of key rotation policy. + Attributes *KeyRotationPolicyAttributes + + // The lifetimeActions for key rotation action. + LifetimeActions []*LifetimeAction +} + +// SKU details +type SKU struct { + // REQUIRED; SKU family name + Family *SKUFamily + + // REQUIRED; SKU name to specify whether the key vault is a standard vault or a premium vault. + Name *SKUName +} + +// Secret - Resource information with extended details. +type Secret struct { + // REQUIRED; Properties of the secret + Properties *SecretProperties + + // READ-ONLY; Fully qualified identifier of the key vault resource. + ID *string + + // READ-ONLY; Azure location of the key vault resource. + Location *string + + // READ-ONLY; Name of the key vault resource. + Name *string + + // READ-ONLY; Tags assigned to the key vault resource. + Tags map[string]*string + + // READ-ONLY; Resource type of the key vault resource. + Type *string +} + +// SecretAttributes - The secret management attributes. +type SecretAttributes struct { + // Determines whether the object is enabled. + Enabled *bool + + // Expiry date in seconds since 1970-01-01T00:00:00Z. + Expires *time.Time + + // Not before date in seconds since 1970-01-01T00:00:00Z. + NotBefore *time.Time + + // READ-ONLY; Creation time in seconds since 1970-01-01T00:00:00Z. + Created *time.Time + + // READ-ONLY; Last updated time in seconds since 1970-01-01T00:00:00Z. + Updated *time.Time +} + +// SecretCreateOrUpdateParameters - Parameters for creating or updating a secret +type SecretCreateOrUpdateParameters struct { + // REQUIRED; Properties of the secret + Properties *SecretProperties + + // The tags that will be assigned to the secret. + Tags map[string]*string +} + +// SecretListResult - List of secrets +type SecretListResult struct { + // The URL to get the next set of secrets. + NextLink *string + + // The list of secrets. + Value []*Secret +} + +// SecretPatchParameters - Parameters for patching a secret +type SecretPatchParameters struct { + // Properties of the secret + Properties *SecretPatchProperties + + // The tags that will be assigned to the secret. + Tags map[string]*string +} + +// SecretPatchProperties - Properties of the secret +type SecretPatchProperties struct { + // The attributes of the secret. + Attributes *SecretAttributes + + // The content type of the secret. + ContentType *string + + // The value of the secret. + Value *string +} + +// SecretProperties - Properties of the secret +type SecretProperties struct { + // The attributes of the secret. + Attributes *SecretAttributes + + // The content type of the secret. + ContentType *string + + // The value of the secret. NOTE: 'value' will never be returned from the service, as APIs using this model are is intended + // for internal use in ARM deployments. Users should use the data-plane REST + // service for interaction with vault secrets. + Value *string + + // READ-ONLY; The URI to retrieve the current version of the secret. + SecretURI *string + + // READ-ONLY; The URI to retrieve the specific version of the secret. + SecretURIWithVersion *string +} + +// ServiceSpecification - One property of operation, include log specifications. +type ServiceSpecification struct { + // Log specifications of operation. + LogSpecifications []*LogSpecification + + // Metric specifications of operation. + MetricSpecifications []*MetricSpecification +} + +// SystemData - Metadata pertaining to creation and last modification of the key vault resource. +type SystemData struct { + // The timestamp of the key vault resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the key vault resource. + CreatedBy *string + + // The type of identity that created the key vault resource. + CreatedByType *IdentityType + + // The timestamp of the key vault resource last modification (UTC). + LastModifiedAt *time.Time + + // The identity that last modified the key vault resource. + LastModifiedBy *string + + // The type of identity that last modified the key vault resource. + LastModifiedByType *IdentityType +} + +type Trigger struct { + // The time duration after key creation to rotate the key. It only applies to rotate. It will be in ISO 8601 duration format. + // Eg: 'P90D', 'P1Y'. + TimeAfterCreate *string + + // The time duration before key expiring to rotate or notify. It will be in ISO 8601 duration format. Eg: 'P90D', 'P1Y'. + TimeBeforeExpiry *string +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} + +// Vault - Resource information with extended details. +type Vault struct { + // REQUIRED; Properties of the vault + Properties *VaultProperties + + // Azure location of the key vault resource. + Location *string + + // Tags assigned to the key vault resource. + Tags map[string]*string + + // READ-ONLY; Fully qualified identifier of the key vault resource. + ID *string + + // READ-ONLY; Name of the key vault resource. + Name *string + + // READ-ONLY; System metadata for the key vault. + SystemData *SystemData + + // READ-ONLY; Resource type of the key vault resource. + Type *string +} + +// VaultAccessPolicyParameters - Parameters for updating the access policy in a vault +type VaultAccessPolicyParameters struct { + // REQUIRED; Properties of the access policy + Properties *VaultAccessPolicyProperties + + // READ-ONLY; The resource id of the access policy. + ID *string + + // READ-ONLY; The resource type of the access policy. + Location *string + + // READ-ONLY; The resource name of the access policy. + Name *string + + // READ-ONLY; The resource name of the access policy. + Type *string +} + +// VaultAccessPolicyProperties - Properties of the vault access policy +type VaultAccessPolicyProperties struct { + // REQUIRED; An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same + // tenant ID as the key vault's tenant ID. + AccessPolicies []*AccessPolicyEntry +} + +// VaultCheckNameAvailabilityParameters - The parameters used to check the availability of the vault name. +type VaultCheckNameAvailabilityParameters struct { + // REQUIRED; The vault name. + Name *string + + // CONSTANT; The type of resource, Microsoft.KeyVault/vaults + // Field has constant value "Microsoft.KeyVault/vaults", any specified value is ignored. + Type *string +} + +// VaultCreateOrUpdateParameters - Parameters for creating or updating a vault +type VaultCreateOrUpdateParameters struct { + // REQUIRED; The supported Azure location where the key vault should be created. + Location *string + + // REQUIRED; Properties of the vault + Properties *VaultProperties + + // The tags that will be assigned to the key vault. + Tags map[string]*string +} + +// VaultListResult - List of vaults +type VaultListResult struct { + // The URL to get the next set of vaults. + NextLink *string + + // The list of vaults. + Value []*Vault +} + +// VaultPatchParameters - Parameters for creating or updating a vault +type VaultPatchParameters struct { + // Properties of the vault + Properties *VaultPatchProperties + + // The tags that will be assigned to the key vault. + Tags map[string]*string +} + +// VaultPatchProperties - Properties of the vault +type VaultPatchProperties struct { + // An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + // ID as the key vault's tenant ID. + AccessPolicies []*AccessPolicyEntry + + // The vault's create mode to indicate whether the vault need to be recovered or not. + CreateMode *CreateMode + + // Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + // protection against purge for this vault and its content - only the Key Vault + // service may initiate a hard, irrecoverable deletion. The setting is effective only if soft delete is also enabled. Enabling + // this functionality is irreversible - that is, the property does not accept + // false as its value. + EnablePurgeProtection *bool + + // Property that controls how data actions are authorized. When true, the key vault will use Role Based Access Control (RBAC) + // for authorization of data actions, and the access policies specified in vault + // properties will be ignored. When false, the key vault will use the access policies specified in vault properties, and any + // policy stored on Azure Resource Manager will be ignored. If null or not + // specified, the value of this property will not change. + EnableRbacAuthorization *bool + + // Property to specify whether the 'soft delete' functionality is enabled for this key vault. Once set to true, it cannot + // be reverted to false. + EnableSoftDelete *bool + + // Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + // vault. + EnabledForDeployment *bool + + // Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + EnabledForDiskEncryption *bool + + // Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + EnabledForTemplateDeployment *bool + + // A collection of rules governing the accessibility of the vault from specific network locations. + NetworkACLs *NetworkRuleSet + + // Property to specify whether the vault will accept traffic from public internet. If set to 'disabled' all traffic except + // private endpoint traffic and that that originates from trusted services will be + // blocked. This will override the set firewall rules, meaning that even if the firewall rules are present we will not honor + // the rules. + PublicNetworkAccess *string + + // SKU details + SKU *SKU + + // softDelete data retention days. It accepts >=7 and <=90. + SoftDeleteRetentionInDays *int32 + + // The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + TenantID *string +} + +// VaultProperties - Properties of the vault +type VaultProperties struct { + // REQUIRED; SKU details + SKU *SKU + + // REQUIRED; The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + TenantID *string + + // An array of 0 to 1024 identities that have access to the key vault. All identities in the array must use the same tenant + // ID as the key vault's tenant ID. When createMode is set to recover, access + // policies are not required. Otherwise, access policies are required. + AccessPolicies []*AccessPolicyEntry + + // The vault's create mode to indicate whether the vault need to be recovered or not. + CreateMode *CreateMode + + // Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + // protection against purge for this vault and its content - only the Key Vault + // service may initiate a hard, irrecoverable deletion. The setting is effective only if soft delete is also enabled. Enabling + // this functionality is irreversible - that is, the property does not accept + // false as its value. + EnablePurgeProtection *bool + + // Property that controls how data actions are authorized. When true, the key vault will use Role Based Access Control (RBAC) + // for authorization of data actions, and the access policies specified in vault + // properties will be ignored. When false, the key vault will use the access policies specified in vault properties, and any + // policy stored on Azure Resource Manager will be ignored. If null or not + // specified, the vault is created with the default value of false. Note that management actions are always authorized with + // RBAC. + EnableRbacAuthorization *bool + + // Property to specify whether the 'soft delete' functionality is enabled for this key vault. If it's not set to any value(true + // or false) when creating new key vault, it will be set to true by default. + // Once set to true, it cannot be reverted to false. + EnableSoftDelete *bool + + // Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + // vault. + EnabledForDeployment *bool + + // Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + EnabledForDiskEncryption *bool + + // Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + EnabledForTemplateDeployment *bool + + // Rules governing the accessibility of the key vault from specific network locations. + NetworkACLs *NetworkRuleSet + + // Provisioning state of the vault. + ProvisioningState *VaultProvisioningState + + // Property to specify whether the vault will accept traffic from public internet. If set to 'disabled' all traffic except + // private endpoint traffic and that that originates from trusted services will be + // blocked. This will override the set firewall rules, meaning that even if the firewall rules are present we will not honor + // the rules. + PublicNetworkAccess *string + + // softDelete data retention days. It accepts >=7 and <=90. + SoftDeleteRetentionInDays *int32 + + // The URI of the vault for performing operations on keys and secrets. + VaultURI *string + + // READ-ONLY; The resource id of HSM Pool. + HsmPoolResourceID *string + + // READ-ONLY; List of private endpoint connections associated with the key vault. + PrivateEndpointConnections []*PrivateEndpointConnectionItem +} + +// VirtualNetworkRule - A rule governing the accessibility of a vault from a specific virtual network. +type VirtualNetworkRule struct { + // REQUIRED; Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. + ID *string + + // Property to specify whether NRP will ignore the check if parent subnet has serviceEndpoints configured. + IgnoreMissingVnetServiceEndpoint *bool +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models_serde.go new file mode 100644 index 0000000000..2efa49ee3a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/models_serde.go @@ -0,0 +1,3636 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "encoding/json" + "fmt" + "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/azcore/to" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AccessPolicyEntry. +func (a AccessPolicyEntry) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationId", a.ApplicationID) + populate(objectMap, "objectId", a.ObjectID) + populate(objectMap, "permissions", a.Permissions) + populate(objectMap, "tenantId", a.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccessPolicyEntry. +func (a *AccessPolicyEntry) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applicationId": + err = unpopulate(val, "ApplicationID", &a.ApplicationID) + delete(rawMsg, key) + case "objectId": + err = unpopulate(val, "ObjectID", &a.ObjectID) + delete(rawMsg, key) + case "permissions": + err = unpopulate(val, "Permissions", &a.Permissions) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &a.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Action. +func (a Action) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Action. +func (a *Action) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckMhsmNameAvailabilityParameters. +func (c CheckMhsmNameAvailabilityParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckMhsmNameAvailabilityParameters. +func (c *CheckMhsmNameAvailabilityParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckMhsmNameAvailabilityResult. +func (c CheckMhsmNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", c.Message) + populate(objectMap, "nameAvailable", c.NameAvailable) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckMhsmNameAvailabilityResult. +func (c *CheckMhsmNameAvailabilityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &c.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResult. +func (c CheckNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", c.Message) + populate(objectMap, "nameAvailable", c.NameAvailable) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResult. +func (c *CheckNameAvailabilityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &c.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedManagedHsm. +func (d DeletedManagedHsm) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedManagedHsm. +func (d *DeletedManagedHsm) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedManagedHsmListResult. +func (d DeletedManagedHsmListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedManagedHsmListResult. +func (d *DeletedManagedHsmListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedManagedHsmProperties. +func (d DeletedManagedHsmProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeRFC3339(objectMap, "deletionDate", d.DeletionDate) + populate(objectMap, "location", d.Location) + populate(objectMap, "mhsmId", d.MhsmID) + populate(objectMap, "purgeProtectionEnabled", d.PurgeProtectionEnabled) + populateTimeRFC3339(objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedManagedHsmProperties. +func (d *DeletedManagedHsmProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deletionDate": + err = unpopulateTimeRFC3339(val, "DeletionDate", &d.DeletionDate) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "mhsmId": + err = unpopulate(val, "MhsmID", &d.MhsmID) + delete(rawMsg, key) + case "purgeProtectionEnabled": + err = unpopulate(val, "PurgeProtectionEnabled", &d.PurgeProtectionEnabled) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeRFC3339(val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedVault. +func (d DeletedVault) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedVault. +func (d *DeletedVault) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedVaultListResult. +func (d DeletedVaultListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedVaultListResult. +func (d *DeletedVaultListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedVaultProperties. +func (d DeletedVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeRFC3339(objectMap, "deletionDate", d.DeletionDate) + populate(objectMap, "location", d.Location) + populate(objectMap, "purgeProtectionEnabled", d.PurgeProtectionEnabled) + populateTimeRFC3339(objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "vaultId", d.VaultID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedVaultProperties. +func (d *DeletedVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deletionDate": + err = unpopulateTimeRFC3339(val, "DeletionDate", &d.DeletionDate) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "purgeProtectionEnabled": + err = unpopulate(val, "PurgeProtectionEnabled", &d.PurgeProtectionEnabled) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeRFC3339(val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "vaultId": + err = unpopulate(val, "VaultID", &d.VaultID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DimensionProperties. +func (d DimensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "name", d.Name) + populate(objectMap, "toBeExportedForShoebox", d.ToBeExportedForShoebox) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DimensionProperties. +func (d *DimensionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "toBeExportedForShoebox": + err = unpopulate(val, "ToBeExportedForShoebox", &d.ToBeExportedForShoebox) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IPRule. +func (i IPRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPRule. +func (i *IPRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Key. +func (k Key) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", k.ID) + populate(objectMap, "location", k.Location) + populate(objectMap, "name", k.Name) + populate(objectMap, "properties", k.Properties) + populate(objectMap, "tags", k.Tags) + populate(objectMap, "type", k.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Key. +func (k *Key) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &k.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &k.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &k.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &k.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &k.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyAttributes. +func (k KeyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "created", k.Created) + populate(objectMap, "enabled", k.Enabled) + populate(objectMap, "exp", k.Expires) + populate(objectMap, "exportable", k.Exportable) + populate(objectMap, "nbf", k.NotBefore) + populate(objectMap, "recoveryLevel", k.RecoveryLevel) + populate(objectMap, "updated", k.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyAttributes. +func (k *KeyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulate(val, "Created", &k.Created) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &k.Enabled) + delete(rawMsg, key) + case "exp": + err = unpopulate(val, "Expires", &k.Expires) + delete(rawMsg, key) + case "exportable": + err = unpopulate(val, "Exportable", &k.Exportable) + delete(rawMsg, key) + case "nbf": + err = unpopulate(val, "NotBefore", &k.NotBefore) + delete(rawMsg, key) + case "recoveryLevel": + err = unpopulate(val, "RecoveryLevel", &k.RecoveryLevel) + delete(rawMsg, key) + case "updated": + err = unpopulate(val, "Updated", &k.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyCreateParameters. +func (k KeyCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", k.Properties) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyCreateParameters. +func (k *KeyCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &k.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyListResult. +func (k KeyListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", k.NextLink) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyListResult. +func (k *KeyListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &k.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyProperties. +func (k KeyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "curveName", k.CurveName) + populate(objectMap, "keyOps", k.KeyOps) + populate(objectMap, "keySize", k.KeySize) + populate(objectMap, "keyUri", k.KeyURI) + populate(objectMap, "keyUriWithVersion", k.KeyURIWithVersion) + populate(objectMap, "kty", k.Kty) + populate(objectMap, "release_policy", k.ReleasePolicy) + populate(objectMap, "rotationPolicy", k.RotationPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyProperties. +func (k *KeyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "curveName": + err = unpopulate(val, "CurveName", &k.CurveName) + delete(rawMsg, key) + case "keyOps": + err = unpopulate(val, "KeyOps", &k.KeyOps) + delete(rawMsg, key) + case "keySize": + err = unpopulate(val, "KeySize", &k.KeySize) + delete(rawMsg, key) + case "keyUri": + err = unpopulate(val, "KeyURI", &k.KeyURI) + delete(rawMsg, key) + case "keyUriWithVersion": + err = unpopulate(val, "KeyURIWithVersion", &k.KeyURIWithVersion) + delete(rawMsg, key) + case "kty": + err = unpopulate(val, "Kty", &k.Kty) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &k.ReleasePolicy) + delete(rawMsg, key) + case "rotationPolicy": + err = unpopulate(val, "RotationPolicy", &k.RotationPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyReleasePolicy. +func (k KeyReleasePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", k.ContentType) + populateByteArray(objectMap, "data", k.Data, runtime.Base64URLFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyReleasePolicy. +func (k *KeyReleasePolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &k.ContentType) + delete(rawMsg, key) + case "data": + err = runtime.DecodeByteArray(string(val), &k.Data, runtime.Base64URLFormat) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyRotationPolicyAttributes. +func (k KeyRotationPolicyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "created", k.Created) + populate(objectMap, "expiryTime", k.ExpiryTime) + populate(objectMap, "updated", k.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyRotationPolicyAttributes. +func (k *KeyRotationPolicyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulate(val, "Created", &k.Created) + delete(rawMsg, key) + case "expiryTime": + err = unpopulate(val, "ExpiryTime", &k.ExpiryTime) + delete(rawMsg, key) + case "updated": + err = unpopulate(val, "Updated", &k.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeAction. +func (l LifetimeAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", l.Action) + populate(objectMap, "trigger", l.Trigger) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeAction. +func (l *LifetimeAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &l.Action) + delete(rawMsg, key) + case "trigger": + err = unpopulate(val, "Trigger", &l.Trigger) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LogSpecification. +func (l LogSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobDuration", l.BlobDuration) + populate(objectMap, "displayName", l.DisplayName) + populate(objectMap, "name", l.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LogSpecification. +func (l *LogSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blobDuration": + err = unpopulate(val, "BlobDuration", &l.BlobDuration) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &l.DisplayName) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMGeoReplicatedRegion. +func (m MHSMGeoReplicatedRegion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isPrimary", m.IsPrimary) + populate(objectMap, "name", m.Name) + populate(objectMap, "provisioningState", m.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMGeoReplicatedRegion. +func (m *MHSMGeoReplicatedRegion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isPrimary": + err = unpopulate(val, "IsPrimary", &m.IsPrimary) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMIPRule. +func (m MHSMIPRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMIPRule. +func (m *MHSMIPRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMNetworkRuleSet. +func (m MHSMNetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypass", m.Bypass) + populate(objectMap, "defaultAction", m.DefaultAction) + populate(objectMap, "ipRules", m.IPRules) + populate(objectMap, "virtualNetworkRules", m.VirtualNetworkRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMNetworkRuleSet. +func (m *MHSMNetworkRuleSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bypass": + err = unpopulate(val, "Bypass", &m.Bypass) + delete(rawMsg, key) + case "defaultAction": + err = unpopulate(val, "DefaultAction", &m.DefaultAction) + delete(rawMsg, key) + case "ipRules": + err = unpopulate(val, "IPRules", &m.IPRules) + delete(rawMsg, key) + case "virtualNetworkRules": + err = unpopulate(val, "VirtualNetworkRules", &m.VirtualNetworkRules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateEndpoint. +func (m MHSMPrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateEndpoint. +func (m *MHSMPrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateEndpointConnection. +func (m MHSMPrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", m.Etag) + populate(objectMap, "id", m.ID) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "sku", m.SKU) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateEndpointConnection. +func (m *MHSMPrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &m.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &m.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateEndpointConnectionItem. +func (m MHSMPrivateEndpointConnectionItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", m.Etag) + populate(objectMap, "id", m.ID) + populate(objectMap, "properties", m.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateEndpointConnectionItem. +func (m *MHSMPrivateEndpointConnectionItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &m.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateEndpointConnectionProperties. +func (m MHSMPrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateEndpoint", m.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", m.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", m.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateEndpointConnectionProperties. +func (m *MHSMPrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &m.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &m.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateEndpointConnectionsListResult. +func (m MHSMPrivateEndpointConnectionsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateEndpointConnectionsListResult. +func (m *MHSMPrivateEndpointConnectionsListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateLinkResource. +func (m MHSMPrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "sku", m.SKU) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateLinkResource. +func (m *MHSMPrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &m.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateLinkResourceListResult. +func (m MHSMPrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateLinkResourceListResult. +func (m *MHSMPrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateLinkResourceProperties. +func (m MHSMPrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", m.GroupID) + populate(objectMap, "requiredMembers", m.RequiredMembers) + populate(objectMap, "requiredZoneNames", m.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateLinkResourceProperties. +func (m *MHSMPrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupId": + err = unpopulate(val, "GroupID", &m.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &m.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &m.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMPrivateLinkServiceConnectionState. +func (m MHSMPrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionsRequired", m.ActionsRequired) + populate(objectMap, "description", m.Description) + populate(objectMap, "status", m.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMPrivateLinkServiceConnectionState. +func (m *MHSMPrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionsRequired": + err = unpopulate(val, "ActionsRequired", &m.ActionsRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &m.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMRegionsListResult. +func (m MHSMRegionsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMRegionsListResult. +func (m *MHSMRegionsListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MHSMVirtualNetworkRule. +func (m MHSMVirtualNetworkRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MHSMVirtualNetworkRule. +func (m *MHSMVirtualNetworkRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHSMSecurityDomainProperties. +func (m ManagedHSMSecurityDomainProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activationStatus", m.ActivationStatus) + populate(objectMap, "activationStatusMessage", m.ActivationStatusMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHSMSecurityDomainProperties. +func (m *ManagedHSMSecurityDomainProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "activationStatus": + err = unpopulate(val, "ActivationStatus", &m.ActivationStatus) + delete(rawMsg, key) + case "activationStatusMessage": + err = unpopulate(val, "ActivationStatusMessage", &m.ActivationStatusMessage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsm. +func (m ManagedHsm) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "sku", m.SKU) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsm. +func (m *ManagedHsm) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &m.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmAction. +func (m ManagedHsmAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmAction. +func (m *ManagedHsmAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKey. +func (m ManagedHsmKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKey. +func (m *ManagedHsmKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKeyAttributes. +func (m ManagedHsmKeyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "created", m.Created) + populate(objectMap, "enabled", m.Enabled) + populate(objectMap, "exp", m.Expires) + populate(objectMap, "exportable", m.Exportable) + populate(objectMap, "nbf", m.NotBefore) + populate(objectMap, "recoveryLevel", m.RecoveryLevel) + populate(objectMap, "updated", m.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKeyAttributes. +func (m *ManagedHsmKeyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulate(val, "Created", &m.Created) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &m.Enabled) + delete(rawMsg, key) + case "exp": + err = unpopulate(val, "Expires", &m.Expires) + delete(rawMsg, key) + case "exportable": + err = unpopulate(val, "Exportable", &m.Exportable) + delete(rawMsg, key) + case "nbf": + err = unpopulate(val, "NotBefore", &m.NotBefore) + delete(rawMsg, key) + case "recoveryLevel": + err = unpopulate(val, "RecoveryLevel", &m.RecoveryLevel) + delete(rawMsg, key) + case "updated": + err = unpopulate(val, "Updated", &m.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKeyCreateParameters. +func (m ManagedHsmKeyCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "tags", m.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKeyCreateParameters. +func (m *ManagedHsmKeyCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKeyListResult. +func (m ManagedHsmKeyListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKeyListResult. +func (m *ManagedHsmKeyListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKeyProperties. +func (m ManagedHsmKeyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", m.Attributes) + populate(objectMap, "curveName", m.CurveName) + populate(objectMap, "keyOps", m.KeyOps) + populate(objectMap, "keySize", m.KeySize) + populate(objectMap, "keyUri", m.KeyURI) + populate(objectMap, "keyUriWithVersion", m.KeyURIWithVersion) + populate(objectMap, "kty", m.Kty) + populate(objectMap, "release_policy", m.ReleasePolicy) + populate(objectMap, "rotationPolicy", m.RotationPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKeyProperties. +func (m *ManagedHsmKeyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &m.Attributes) + delete(rawMsg, key) + case "curveName": + err = unpopulate(val, "CurveName", &m.CurveName) + delete(rawMsg, key) + case "keyOps": + err = unpopulate(val, "KeyOps", &m.KeyOps) + delete(rawMsg, key) + case "keySize": + err = unpopulate(val, "KeySize", &m.KeySize) + delete(rawMsg, key) + case "keyUri": + err = unpopulate(val, "KeyURI", &m.KeyURI) + delete(rawMsg, key) + case "keyUriWithVersion": + err = unpopulate(val, "KeyURIWithVersion", &m.KeyURIWithVersion) + delete(rawMsg, key) + case "kty": + err = unpopulate(val, "Kty", &m.Kty) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &m.ReleasePolicy) + delete(rawMsg, key) + case "rotationPolicy": + err = unpopulate(val, "RotationPolicy", &m.RotationPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKeyReleasePolicy. +func (m ManagedHsmKeyReleasePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", m.ContentType) + populateByteArray(objectMap, "data", m.Data, runtime.Base64URLFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKeyReleasePolicy. +func (m *ManagedHsmKeyReleasePolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &m.ContentType) + delete(rawMsg, key) + case "data": + err = runtime.DecodeByteArray(string(val), &m.Data, runtime.Base64URLFormat) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmKeyRotationPolicyAttributes. +func (m ManagedHsmKeyRotationPolicyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "created", m.Created) + populate(objectMap, "expiryTime", m.ExpiryTime) + populate(objectMap, "updated", m.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmKeyRotationPolicyAttributes. +func (m *ManagedHsmKeyRotationPolicyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulate(val, "Created", &m.Created) + delete(rawMsg, key) + case "expiryTime": + err = unpopulate(val, "ExpiryTime", &m.ExpiryTime) + delete(rawMsg, key) + case "updated": + err = unpopulate(val, "Updated", &m.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmLifetimeAction. +func (m ManagedHsmLifetimeAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", m.Action) + populate(objectMap, "trigger", m.Trigger) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmLifetimeAction. +func (m *ManagedHsmLifetimeAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &m.Action) + delete(rawMsg, key) + case "trigger": + err = unpopulate(val, "Trigger", &m.Trigger) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmListResult. +func (m ManagedHsmListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmListResult. +func (m *ManagedHsmListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmProperties. +func (m ManagedHsmProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "createMode", m.CreateMode) + populate(objectMap, "enablePurgeProtection", m.EnablePurgeProtection) + populate(objectMap, "enableSoftDelete", m.EnableSoftDelete) + populate(objectMap, "hsmUri", m.HsmURI) + populate(objectMap, "initialAdminObjectIds", m.InitialAdminObjectIDs) + populate(objectMap, "networkAcls", m.NetworkACLs) + populate(objectMap, "privateEndpointConnections", m.PrivateEndpointConnections) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "publicNetworkAccess", m.PublicNetworkAccess) + populate(objectMap, "regions", m.Regions) + populateTimeRFC3339(objectMap, "scheduledPurgeDate", m.ScheduledPurgeDate) + populate(objectMap, "securityDomainProperties", m.SecurityDomainProperties) + populate(objectMap, "softDeleteRetentionInDays", m.SoftDeleteRetentionInDays) + populate(objectMap, "statusMessage", m.StatusMessage) + populate(objectMap, "tenantId", m.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmProperties. +func (m *ManagedHsmProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createMode": + err = unpopulate(val, "CreateMode", &m.CreateMode) + delete(rawMsg, key) + case "enablePurgeProtection": + err = unpopulate(val, "EnablePurgeProtection", &m.EnablePurgeProtection) + delete(rawMsg, key) + case "enableSoftDelete": + err = unpopulate(val, "EnableSoftDelete", &m.EnableSoftDelete) + delete(rawMsg, key) + case "hsmUri": + err = unpopulate(val, "HsmURI", &m.HsmURI) + delete(rawMsg, key) + case "initialAdminObjectIds": + err = unpopulate(val, "InitialAdminObjectIDs", &m.InitialAdminObjectIDs) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkACLs", &m.NetworkACLs) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &m.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &m.PublicNetworkAccess) + delete(rawMsg, key) + case "regions": + err = unpopulate(val, "Regions", &m.Regions) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeRFC3339(val, "ScheduledPurgeDate", &m.ScheduledPurgeDate) + delete(rawMsg, key) + case "securityDomainProperties": + err = unpopulate(val, "SecurityDomainProperties", &m.SecurityDomainProperties) + delete(rawMsg, key) + case "softDeleteRetentionInDays": + err = unpopulate(val, "SoftDeleteRetentionInDays", &m.SoftDeleteRetentionInDays) + delete(rawMsg, key) + case "statusMessage": + err = unpopulate(val, "StatusMessage", &m.StatusMessage) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmRotationPolicy. +func (m ManagedHsmRotationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", m.Attributes) + populate(objectMap, "lifetimeActions", m.LifetimeActions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmRotationPolicy. +func (m *ManagedHsmRotationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &m.Attributes) + delete(rawMsg, key) + case "lifetimeActions": + err = unpopulate(val, "LifetimeActions", &m.LifetimeActions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmSKU. +func (m ManagedHsmSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if m.Family == nil { + m.Family = to.Ptr(ManagedHsmSKUFamilyB) + } + populate(objectMap, "family", m.Family) + populate(objectMap, "name", m.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmSKU. +func (m *ManagedHsmSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "family": + err = unpopulate(val, "Family", &m.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedHsmTrigger. +func (m ManagedHsmTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "timeAfterCreate", m.TimeAfterCreate) + populate(objectMap, "timeBeforeExpiry", m.TimeBeforeExpiry) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedHsmTrigger. +func (m *ManagedHsmTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "timeAfterCreate": + err = unpopulate(val, "TimeAfterCreate", &m.TimeAfterCreate) + delete(rawMsg, key) + case "timeBeforeExpiry": + err = unpopulate(val, "TimeBeforeExpiry", &m.TimeBeforeExpiry) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetricSpecification. +func (m MetricSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationType", m.AggregationType) + populate(objectMap, "dimensions", m.Dimensions) + populate(objectMap, "displayDescription", m.DisplayDescription) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "fillGapWithZero", m.FillGapWithZero) + populate(objectMap, "internalMetricName", m.InternalMetricName) + populate(objectMap, "lockAggregationType", m.LockAggregationType) + populate(objectMap, "name", m.Name) + populate(objectMap, "supportedAggregationTypes", m.SupportedAggregationTypes) + populate(objectMap, "supportedTimeGrainTypes", m.SupportedTimeGrainTypes) + populate(objectMap, "unit", m.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetricSpecification. +func (m *MetricSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aggregationType": + err = unpopulate(val, "AggregationType", &m.AggregationType) + delete(rawMsg, key) + case "dimensions": + err = unpopulate(val, "Dimensions", &m.Dimensions) + delete(rawMsg, key) + case "displayDescription": + err = unpopulate(val, "DisplayDescription", &m.DisplayDescription) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &m.DisplayName) + delete(rawMsg, key) + case "fillGapWithZero": + err = unpopulate(val, "FillGapWithZero", &m.FillGapWithZero) + delete(rawMsg, key) + case "internalMetricName": + err = unpopulate(val, "InternalMetricName", &m.InternalMetricName) + delete(rawMsg, key) + case "lockAggregationType": + err = unpopulate(val, "LockAggregationType", &m.LockAggregationType) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "supportedAggregationTypes": + err = unpopulate(val, "SupportedAggregationTypes", &m.SupportedAggregationTypes) + delete(rawMsg, key) + case "supportedTimeGrainTypes": + err = unpopulate(val, "SupportedTimeGrainTypes", &m.SupportedTimeGrainTypes) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &m.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkRuleSet. +func (n NetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypass", n.Bypass) + populate(objectMap, "defaultAction", n.DefaultAction) + populate(objectMap, "ipRules", n.IPRules) + populate(objectMap, "virtualNetworkRules", n.VirtualNetworkRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkRuleSet. +func (n *NetworkRuleSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bypass": + err = unpopulate(val, "Bypass", &n.Bypass) + delete(rawMsg, key) + case "defaultAction": + err = unpopulate(val, "DefaultAction", &n.DefaultAction) + delete(rawMsg, key) + case "ipRules": + err = unpopulate(val, "IPRules", &n.IPRules) + delete(rawMsg, key) + case "virtualNetworkRules": + err = unpopulate(val, "VirtualNetworkRules", &n.VirtualNetworkRules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.OperationProperties) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "OperationProperties", &o.OperationProperties) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationProperties. +func (o OperationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceSpecification", o.ServiceSpecification) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationProperties. +func (o *OperationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "serviceSpecification": + err = unpopulate(val, "ServiceSpecification", &o.ServiceSpecification) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Permissions. +func (p Permissions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificates", p.Certificates) + populate(objectMap, "keys", p.Keys) + populate(objectMap, "secrets", p.Secrets) + populate(objectMap, "storage", p.Storage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Permissions. +func (p *Permissions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificates": + err = unpopulate(val, "Certificates", &p.Certificates) + delete(rawMsg, key) + case "keys": + err = unpopulate(val, "Keys", &p.Keys) + delete(rawMsg, key) + case "secrets": + err = unpopulate(val, "Secrets", &p.Secrets) + delete(rawMsg, key) + case "storage": + err = unpopulate(val, "Storage", &p.Storage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpoint. +func (p *PrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnection. +func (p *PrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionItem. +func (p PrivateEndpointConnectionItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionItem. +func (p *PrivateEndpointConnectionItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionListResult. +func (p *PrivateEndpointConnectionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionProperties. +func (p *PrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResource. +func (p *PrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceListResult. +func (p *PrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceProperties. +func (p *PrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupId": + err = unpopulate(val, "GroupID", &p.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &p.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &p.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionState. +func (p PrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionsRequired", p.ActionsRequired) + populate(objectMap, "description", p.Description) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionState. +func (p *PrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionsRequired": + err = unpopulate(val, "ActionsRequired", &p.ActionsRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. +func (r *Resource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceListResult. +func (r ResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceListResult. +func (r *ResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RotationPolicy. +func (r RotationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", r.Attributes) + populate(objectMap, "lifetimeActions", r.LifetimeActions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RotationPolicy. +func (r *RotationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &r.Attributes) + delete(rawMsg, key) + case "lifetimeActions": + err = unpopulate(val, "LifetimeActions", &r.LifetimeActions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if s.Family == nil { + s.Family = to.Ptr(SKUFamilyA) + } + populate(objectMap, "family", s.Family) + populate(objectMap, "name", s.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "family": + err = unpopulate(val, "Family", &s.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Secret. +func (s Secret) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Secret. +func (s *Secret) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretAttributes. +func (s SecretAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeUnix(objectMap, "created", s.Created) + populate(objectMap, "enabled", s.Enabled) + populateTimeUnix(objectMap, "exp", s.Expires) + populateTimeUnix(objectMap, "nbf", s.NotBefore) + populateTimeUnix(objectMap, "updated", s.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretAttributes. +func (s *SecretAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulateTimeUnix(val, "Created", &s.Created) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &s.Enabled) + delete(rawMsg, key) + case "exp": + err = unpopulateTimeUnix(val, "Expires", &s.Expires) + delete(rawMsg, key) + case "nbf": + err = unpopulateTimeUnix(val, "NotBefore", &s.NotBefore) + delete(rawMsg, key) + case "updated": + err = unpopulateTimeUnix(val, "Updated", &s.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretCreateOrUpdateParameters. +func (s SecretCreateOrUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretCreateOrUpdateParameters. +func (s *SecretCreateOrUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretListResult. +func (s SecretListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretListResult. +func (s *SecretListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretPatchParameters. +func (s SecretPatchParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretPatchParameters. +func (s *SecretPatchParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretPatchProperties. +func (s SecretPatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", s.Attributes) + populate(objectMap, "contentType", s.ContentType) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretPatchProperties. +func (s *SecretPatchProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &s.Attributes) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &s.ContentType) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretProperties. +func (s SecretProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", s.Attributes) + populate(objectMap, "contentType", s.ContentType) + populate(objectMap, "secretUri", s.SecretURI) + populate(objectMap, "secretUriWithVersion", s.SecretURIWithVersion) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretProperties. +func (s *SecretProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &s.Attributes) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &s.ContentType) + delete(rawMsg, key) + case "secretUri": + err = unpopulate(val, "SecretURI", &s.SecretURI) + delete(rawMsg, key) + case "secretUriWithVersion": + err = unpopulate(val, "SecretURIWithVersion", &s.SecretURIWithVersion) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceSpecification. +func (s ServiceSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "logSpecifications", s.LogSpecifications) + populate(objectMap, "metricSpecifications", s.MetricSpecifications) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceSpecification. +func (s *ServiceSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "logSpecifications": + err = unpopulate(val, "LogSpecifications", &s.LogSpecifications) + delete(rawMsg, key) + case "metricSpecifications": + err = unpopulate(val, "MetricSpecifications", &s.MetricSpecifications) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTimeRFC3339(val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Trigger. +func (t Trigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "timeAfterCreate", t.TimeAfterCreate) + populate(objectMap, "timeBeforeExpiry", t.TimeBeforeExpiry) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Trigger. +func (t *Trigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "timeAfterCreate": + err = unpopulate(val, "TimeAfterCreate", &t.TimeAfterCreate) + delete(rawMsg, key) + case "timeBeforeExpiry": + err = unpopulate(val, "TimeBeforeExpiry", &t.TimeBeforeExpiry) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Vault. +func (v Vault) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "systemData", v.SystemData) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Vault. +func (v *Vault) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &v.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &v.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultAccessPolicyParameters. +func (v VaultAccessPolicyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultAccessPolicyParameters. +func (v *VaultAccessPolicyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &v.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultAccessPolicyProperties. +func (v VaultAccessPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessPolicies", v.AccessPolicies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultAccessPolicyProperties. +func (v *VaultAccessPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessPolicies": + err = unpopulate(val, "AccessPolicies", &v.AccessPolicies) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultCheckNameAvailabilityParameters. +func (v VaultCheckNameAvailabilityParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + objectMap["type"] = "Microsoft.KeyVault/vaults" + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultCheckNameAvailabilityParameters. +func (v *VaultCheckNameAvailabilityParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultCreateOrUpdateParameters. +func (v VaultCreateOrUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", v.Location) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultCreateOrUpdateParameters. +func (v *VaultCreateOrUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "location": + err = unpopulate(val, "Location", &v.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultListResult. +func (v VaultListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", v.NextLink) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultListResult. +func (v *VaultListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &v.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &v.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultPatchParameters. +func (v VaultPatchParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultPatchParameters. +func (v *VaultPatchParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultPatchProperties. +func (v VaultPatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessPolicies", v.AccessPolicies) + populate(objectMap, "createMode", v.CreateMode) + populate(objectMap, "enablePurgeProtection", v.EnablePurgeProtection) + populate(objectMap, "enableRbacAuthorization", v.EnableRbacAuthorization) + populate(objectMap, "enableSoftDelete", v.EnableSoftDelete) + populate(objectMap, "enabledForDeployment", v.EnabledForDeployment) + populate(objectMap, "enabledForDiskEncryption", v.EnabledForDiskEncryption) + populate(objectMap, "enabledForTemplateDeployment", v.EnabledForTemplateDeployment) + populate(objectMap, "networkAcls", v.NetworkACLs) + populate(objectMap, "publicNetworkAccess", v.PublicNetworkAccess) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "softDeleteRetentionInDays", v.SoftDeleteRetentionInDays) + populate(objectMap, "tenantId", v.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultPatchProperties. +func (v *VaultPatchProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessPolicies": + err = unpopulate(val, "AccessPolicies", &v.AccessPolicies) + delete(rawMsg, key) + case "createMode": + err = unpopulate(val, "CreateMode", &v.CreateMode) + delete(rawMsg, key) + case "enablePurgeProtection": + err = unpopulate(val, "EnablePurgeProtection", &v.EnablePurgeProtection) + delete(rawMsg, key) + case "enableRbacAuthorization": + err = unpopulate(val, "EnableRbacAuthorization", &v.EnableRbacAuthorization) + delete(rawMsg, key) + case "enableSoftDelete": + err = unpopulate(val, "EnableSoftDelete", &v.EnableSoftDelete) + delete(rawMsg, key) + case "enabledForDeployment": + err = unpopulate(val, "EnabledForDeployment", &v.EnabledForDeployment) + delete(rawMsg, key) + case "enabledForDiskEncryption": + err = unpopulate(val, "EnabledForDiskEncryption", &v.EnabledForDiskEncryption) + delete(rawMsg, key) + case "enabledForTemplateDeployment": + err = unpopulate(val, "EnabledForTemplateDeployment", &v.EnabledForTemplateDeployment) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkACLs", &v.NetworkACLs) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &v.PublicNetworkAccess) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + delete(rawMsg, key) + case "softDeleteRetentionInDays": + err = unpopulate(val, "SoftDeleteRetentionInDays", &v.SoftDeleteRetentionInDays) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &v.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultProperties. +func (v VaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessPolicies", v.AccessPolicies) + populate(objectMap, "createMode", v.CreateMode) + populate(objectMap, "enablePurgeProtection", v.EnablePurgeProtection) + populate(objectMap, "enableRbacAuthorization", v.EnableRbacAuthorization) + populate(objectMap, "enableSoftDelete", v.EnableSoftDelete) + populate(objectMap, "enabledForDeployment", v.EnabledForDeployment) + populate(objectMap, "enabledForDiskEncryption", v.EnabledForDiskEncryption) + populate(objectMap, "enabledForTemplateDeployment", v.EnabledForTemplateDeployment) + populate(objectMap, "hsmPoolResourceId", v.HsmPoolResourceID) + populate(objectMap, "networkAcls", v.NetworkACLs) + populate(objectMap, "privateEndpointConnections", v.PrivateEndpointConnections) + populate(objectMap, "provisioningState", v.ProvisioningState) + populate(objectMap, "publicNetworkAccess", v.PublicNetworkAccess) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "softDeleteRetentionInDays", v.SoftDeleteRetentionInDays) + populate(objectMap, "tenantId", v.TenantID) + populate(objectMap, "vaultUri", v.VaultURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultProperties. +func (v *VaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessPolicies": + err = unpopulate(val, "AccessPolicies", &v.AccessPolicies) + delete(rawMsg, key) + case "createMode": + err = unpopulate(val, "CreateMode", &v.CreateMode) + delete(rawMsg, key) + case "enablePurgeProtection": + err = unpopulate(val, "EnablePurgeProtection", &v.EnablePurgeProtection) + delete(rawMsg, key) + case "enableRbacAuthorization": + err = unpopulate(val, "EnableRbacAuthorization", &v.EnableRbacAuthorization) + delete(rawMsg, key) + case "enableSoftDelete": + err = unpopulate(val, "EnableSoftDelete", &v.EnableSoftDelete) + delete(rawMsg, key) + case "enabledForDeployment": + err = unpopulate(val, "EnabledForDeployment", &v.EnabledForDeployment) + delete(rawMsg, key) + case "enabledForDiskEncryption": + err = unpopulate(val, "EnabledForDiskEncryption", &v.EnabledForDiskEncryption) + delete(rawMsg, key) + case "enabledForTemplateDeployment": + err = unpopulate(val, "EnabledForTemplateDeployment", &v.EnabledForTemplateDeployment) + delete(rawMsg, key) + case "hsmPoolResourceId": + err = unpopulate(val, "HsmPoolResourceID", &v.HsmPoolResourceID) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkACLs", &v.NetworkACLs) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &v.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &v.PublicNetworkAccess) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + delete(rawMsg, key) + case "softDeleteRetentionInDays": + err = unpopulate(val, "SoftDeleteRetentionInDays", &v.SoftDeleteRetentionInDays) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &v.TenantID) + delete(rawMsg, key) + case "vaultUri": + err = unpopulate(val, "VaultURI", &v.VaultURI) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkRule. +func (v VirtualNetworkRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "ignoreMissingVnetServiceEndpoint", v.IgnoreMissingVnetServiceEndpoint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkRule. +func (v *VirtualNetworkRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "ignoreMissingVnetServiceEndpoint": + err = unpopulate(val, "IgnoreMissingVnetServiceEndpoint", &v.IgnoreMissingVnetServiceEndpoint) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateByteArray(m map[string]any, k string, b []byte, f runtime.Base64Encoding) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = runtime.EncodeByteArray(b, f) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/operations_client.go new file mode 100644 index 0000000000..2f0aa49292 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/operations_client.go @@ -0,0 +1,93 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName+".OperationsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - Lists all of the available Key Vault Rest API operations. +// +// Generated from API version 2023-07-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return OperationsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OperationsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OperationsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.KeyVault/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/options.go new file mode 100644 index 0000000000..0f35154240 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/options.go @@ -0,0 +1,283 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +// KeysClientCreateIfNotExistOptions contains the optional parameters for the KeysClient.CreateIfNotExist method. +type KeysClientCreateIfNotExistOptions struct { + // placeholder for future optional parameters +} + +// KeysClientGetOptions contains the optional parameters for the KeysClient.Get method. +type KeysClientGetOptions struct { + // placeholder for future optional parameters +} + +// KeysClientGetVersionOptions contains the optional parameters for the KeysClient.GetVersion method. +type KeysClientGetVersionOptions struct { + // placeholder for future optional parameters +} + +// KeysClientListOptions contains the optional parameters for the KeysClient.NewListPager method. +type KeysClientListOptions struct { + // placeholder for future optional parameters +} + +// KeysClientListVersionsOptions contains the optional parameters for the KeysClient.NewListVersionsPager method. +type KeysClientListVersionsOptions struct { + // placeholder for future optional parameters +} + +// MHSMPrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.BeginDelete +// method. +type MHSMPrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// MHSMPrivateEndpointConnectionsClientGetOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.Get +// method. +type MHSMPrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// MHSMPrivateEndpointConnectionsClientListByResourceOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.NewListByResourcePager +// method. +type MHSMPrivateEndpointConnectionsClientListByResourceOptions struct { + // placeholder for future optional parameters +} + +// MHSMPrivateEndpointConnectionsClientPutOptions contains the optional parameters for the MHSMPrivateEndpointConnectionsClient.Put +// method. +type MHSMPrivateEndpointConnectionsClientPutOptions struct { + // placeholder for future optional parameters +} + +// MHSMPrivateLinkResourcesClientListByMHSMResourceOptions contains the optional parameters for the MHSMPrivateLinkResourcesClient.ListByMHSMResource +// method. +type MHSMPrivateLinkResourcesClientListByMHSMResourceOptions struct { + // placeholder for future optional parameters +} + +// MHSMRegionsClientListByResourceOptions contains the optional parameters for the MHSMRegionsClient.NewListByResourcePager +// method. +type MHSMRegionsClientListByResourceOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmKeysClientCreateIfNotExistOptions contains the optional parameters for the ManagedHsmKeysClient.CreateIfNotExist +// method. +type ManagedHsmKeysClientCreateIfNotExistOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmKeysClientGetOptions contains the optional parameters for the ManagedHsmKeysClient.Get method. +type ManagedHsmKeysClientGetOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmKeysClientGetVersionOptions contains the optional parameters for the ManagedHsmKeysClient.GetVersion method. +type ManagedHsmKeysClientGetVersionOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmKeysClientListOptions contains the optional parameters for the ManagedHsmKeysClient.NewListPager method. +type ManagedHsmKeysClientListOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmKeysClientListVersionsOptions contains the optional parameters for the ManagedHsmKeysClient.NewListVersionsPager +// method. +type ManagedHsmKeysClientListVersionsOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmsClientBeginCreateOrUpdateOptions contains the optional parameters for the ManagedHsmsClient.BeginCreateOrUpdate +// method. +type ManagedHsmsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagedHsmsClientBeginDeleteOptions contains the optional parameters for the ManagedHsmsClient.BeginDelete method. +type ManagedHsmsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagedHsmsClientBeginPurgeDeletedOptions contains the optional parameters for the ManagedHsmsClient.BeginPurgeDeleted +// method. +type ManagedHsmsClientBeginPurgeDeletedOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagedHsmsClientBeginUpdateOptions contains the optional parameters for the ManagedHsmsClient.BeginUpdate method. +type ManagedHsmsClientBeginUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ManagedHsmsClientCheckMhsmNameAvailabilityOptions contains the optional parameters for the ManagedHsmsClient.CheckMhsmNameAvailability +// method. +type ManagedHsmsClientCheckMhsmNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmsClientGetDeletedOptions contains the optional parameters for the ManagedHsmsClient.GetDeleted method. +type ManagedHsmsClientGetDeletedOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmsClientGetOptions contains the optional parameters for the ManagedHsmsClient.Get method. +type ManagedHsmsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ManagedHsmsClientListByResourceGroupOptions contains the optional parameters for the ManagedHsmsClient.NewListByResourceGroupPager +// method. +type ManagedHsmsClientListByResourceGroupOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// ManagedHsmsClientListBySubscriptionOptions contains the optional parameters for the ManagedHsmsClient.NewListBySubscriptionPager +// method. +type ManagedHsmsClientListBySubscriptionOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// ManagedHsmsClientListDeletedOptions contains the optional parameters for the ManagedHsmsClient.NewListDeletedPager method. +type ManagedHsmsClientListDeletedOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +type PrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +type PrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientListByResourceOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListByResourcePager +// method. +type PrivateEndpointConnectionsClientListByResourceOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientPutOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Put +// method. +type PrivateEndpointConnectionsClientPutOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesClientListByVaultOptions contains the optional parameters for the PrivateLinkResourcesClient.ListByVault +// method. +type PrivateLinkResourcesClientListByVaultOptions struct { + // placeholder for future optional parameters +} + +// SecretsClientCreateOrUpdateOptions contains the optional parameters for the SecretsClient.CreateOrUpdate method. +type SecretsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SecretsClientGetOptions contains the optional parameters for the SecretsClient.Get method. +type SecretsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SecretsClientListOptions contains the optional parameters for the SecretsClient.NewListPager method. +type SecretsClientListOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// SecretsClientUpdateOptions contains the optional parameters for the SecretsClient.Update method. +type SecretsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientBeginCreateOrUpdateOptions contains the optional parameters for the VaultsClient.BeginCreateOrUpdate method. +type VaultsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VaultsClientBeginPurgeDeletedOptions contains the optional parameters for the VaultsClient.BeginPurgeDeleted method. +type VaultsClientBeginPurgeDeletedOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// VaultsClientCheckNameAvailabilityOptions contains the optional parameters for the VaultsClient.CheckNameAvailability method. +type VaultsClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientDeleteOptions contains the optional parameters for the VaultsClient.Delete method. +type VaultsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientGetDeletedOptions contains the optional parameters for the VaultsClient.GetDeleted method. +type VaultsClientGetDeletedOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientGetOptions contains the optional parameters for the VaultsClient.Get method. +type VaultsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientListByResourceGroupOptions contains the optional parameters for the VaultsClient.NewListByResourceGroupPager +// method. +type VaultsClientListByResourceGroupOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// VaultsClientListBySubscriptionOptions contains the optional parameters for the VaultsClient.NewListBySubscriptionPager +// method. +type VaultsClientListBySubscriptionOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// VaultsClientListDeletedOptions contains the optional parameters for the VaultsClient.NewListDeletedPager method. +type VaultsClientListDeletedOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientListOptions contains the optional parameters for the VaultsClient.NewListPager method. +type VaultsClientListOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// VaultsClientUpdateAccessPolicyOptions contains the optional parameters for the VaultsClient.UpdateAccessPolicy method. +type VaultsClientUpdateAccessPolicyOptions struct { + // placeholder for future optional parameters +} + +// VaultsClientUpdateOptions contains the optional parameters for the VaultsClient.Update method. +type VaultsClientUpdateOptions struct { + // placeholder for future optional parameters +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privateendpointconnections_client.go new file mode 100644 index 0000000000..8e519486d1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privateendpointconnections_client.go @@ -0,0 +1,337 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName+".PrivateEndpointConnectionsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginDelete - Deletes the specified private endpoint connection associated with the key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the key vault. +// - vaultName - The name of the key vault. +// - privateEndpointConnectionName - Name of the private endpoint connection associated with the key vault. +// - options - PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[PrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, vaultName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[PrivateEndpointConnectionsClientDeleteResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[PrivateEndpointConnectionsClientDeleteResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// Delete - Deletes the specified private endpoint connection associated with the key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + req, err := client.deleteCreateRequest(ctx, resourceGroupName, vaultName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified private endpoint connection associated with the key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the key vault. +// - vaultName - The name of the key vault. +// - privateEndpointConnectionName - Name of the private endpoint connection associated with the key vault. +// - options - PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (PrivateEndpointConnectionsClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, vaultName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientGetResponse, error) { + result := PrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourcePager - The List operation gets information about the private endpoint connections associated with the +// vault. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the key vault. +// - vaultName - The name of the key vault. +// - options - PrivateEndpointConnectionsClientListByResourceOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListByResourcePager +// method. +func (client *PrivateEndpointConnectionsClient) NewListByResourcePager(resourceGroupName string, vaultName string, options *PrivateEndpointConnectionsClientListByResourceOptions) *runtime.Pager[PrivateEndpointConnectionsClientListByResourceResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointConnectionsClientListByResourceResponse]{ + More: func(page PrivateEndpointConnectionsClientListByResourceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointConnectionsClientListByResourceResponse) (PrivateEndpointConnectionsClientListByResourceResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listByResourceCreateRequest(ctx, resourceGroupName, vaultName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return PrivateEndpointConnectionsClientListByResourceResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientListByResourceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsClientListByResourceResponse{}, runtime.NewResponseError(resp) + } + return client.listByResourceHandleResponse(resp) + }, + }) +} + +// listByResourceCreateRequest creates the ListByResource request. +func (client *PrivateEndpointConnectionsClient) listByResourceCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *PrivateEndpointConnectionsClientListByResourceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceHandleResponse handles the ListByResource response. +func (client *PrivateEndpointConnectionsClient) listByResourceHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientListByResourceResponse, error) { + result := PrivateEndpointConnectionsClientListByResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsClientListByResourceResponse{}, err + } + return result, nil +} + +// Put - Updates the specified private endpoint connection associated with the key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the key vault. +// - vaultName - The name of the key vault. +// - privateEndpointConnectionName - Name of the private endpoint connection associated with the key vault. +// - properties - The intended state of private endpoint connection. +// - options - PrivateEndpointConnectionsClientPutOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Put +// method. +func (client *PrivateEndpointConnectionsClient) Put(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsClientPutOptions) (PrivateEndpointConnectionsClientPutResponse, error) { + var err error + req, err := client.putCreateRequest(ctx, resourceGroupName, vaultName, privateEndpointConnectionName, properties, options) + if err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *PrivateEndpointConnectionsClient) putCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *PrivateEndpointConnectionsClient) putHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientPutResponse, error) { + result := PrivateEndpointConnectionsClientPutResponse{} + if val := resp.Header.Get("Azure-AsyncOperation"); val != "" { + result.AzureAsyncOperation = &val + } + if val := resp.Header.Get("Retry-After"); val != "" { + retryAfter32, err := strconv.ParseInt(val, 10, 32) + retryAfter := int32(retryAfter32) + if err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + result.RetryAfter = &retryAfter + } + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privatelinkresources_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privatelinkresources_client.go new file mode 100644 index 0000000000..61f7ada623 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/privatelinkresources_client.go @@ -0,0 +1,106 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +type PrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName+".PrivateLinkResourcesClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// ListByVault - Gets the private link resources supported for the key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - Name of the resource group that contains the key vault. +// - vaultName - The name of the key vault. +// - options - PrivateLinkResourcesClientListByVaultOptions contains the optional parameters for the PrivateLinkResourcesClient.ListByVault +// method. +func (client *PrivateLinkResourcesClient) ListByVault(ctx context.Context, resourceGroupName string, vaultName string, options *PrivateLinkResourcesClientListByVaultOptions) (PrivateLinkResourcesClientListByVaultResponse, error) { + var err error + req, err := client.listByVaultCreateRequest(ctx, resourceGroupName, vaultName, options) + if err != nil { + return PrivateLinkResourcesClientListByVaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateLinkResourcesClientListByVaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateLinkResourcesClientListByVaultResponse{}, err + } + resp, err := client.listByVaultHandleResponse(httpResp) + return resp, err +} + +// listByVaultCreateRequest creates the ListByVault request. +func (client *PrivateLinkResourcesClient) listByVaultCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *PrivateLinkResourcesClientListByVaultOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVaultHandleResponse handles the ListByVault response. +func (client *PrivateLinkResourcesClient) listByVaultHandleResponse(resp *http.Response) (PrivateLinkResourcesClientListByVaultResponse, error) { + result := PrivateLinkResourcesClientListByVaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return PrivateLinkResourcesClientListByVaultResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/response_types.go new file mode 100644 index 0000000000..efeaaf1c7d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/response_types.go @@ -0,0 +1,305 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +// KeysClientCreateIfNotExistResponse contains the response from method KeysClient.CreateIfNotExist. +type KeysClientCreateIfNotExistResponse struct { + // The key resource. + Key +} + +// KeysClientGetResponse contains the response from method KeysClient.Get. +type KeysClientGetResponse struct { + // The key resource. + Key +} + +// KeysClientGetVersionResponse contains the response from method KeysClient.GetVersion. +type KeysClientGetVersionResponse struct { + // The key resource. + Key +} + +// KeysClientListResponse contains the response from method KeysClient.NewListPager. +type KeysClientListResponse struct { + // The page of keys. + KeyListResult +} + +// KeysClientListVersionsResponse contains the response from method KeysClient.NewListVersionsPager. +type KeysClientListVersionsResponse struct { + // The page of keys. + KeyListResult +} + +// MHSMPrivateEndpointConnectionsClientDeleteResponse contains the response from method MHSMPrivateEndpointConnectionsClient.BeginDelete. +type MHSMPrivateEndpointConnectionsClientDeleteResponse struct { + // Private endpoint connection resource. + MHSMPrivateEndpointConnection +} + +// MHSMPrivateEndpointConnectionsClientGetResponse contains the response from method MHSMPrivateEndpointConnectionsClient.Get. +type MHSMPrivateEndpointConnectionsClientGetResponse struct { + // Private endpoint connection resource. + MHSMPrivateEndpointConnection +} + +// MHSMPrivateEndpointConnectionsClientListByResourceResponse contains the response from method MHSMPrivateEndpointConnectionsClient.NewListByResourcePager. +type MHSMPrivateEndpointConnectionsClientListByResourceResponse struct { + // List of private endpoint connections associated with a managed HSM Pools + MHSMPrivateEndpointConnectionsListResult +} + +// MHSMPrivateEndpointConnectionsClientPutResponse contains the response from method MHSMPrivateEndpointConnectionsClient.Put. +type MHSMPrivateEndpointConnectionsClientPutResponse struct { + // Private endpoint connection resource. + MHSMPrivateEndpointConnection + + // AzureAsyncOperation contains the information returned from the Azure-AsyncOperation header response. + AzureAsyncOperation *string + + // RetryAfter contains the information returned from the Retry-After header response. + RetryAfter *int32 +} + +// MHSMPrivateLinkResourcesClientListByMHSMResourceResponse contains the response from method MHSMPrivateLinkResourcesClient.ListByMHSMResource. +type MHSMPrivateLinkResourcesClientListByMHSMResourceResponse struct { + // A list of private link resources + MHSMPrivateLinkResourceListResult +} + +// MHSMRegionsClientListByResourceResponse contains the response from method MHSMRegionsClient.NewListByResourcePager. +type MHSMRegionsClientListByResourceResponse struct { + // List of regions associated with a managed HSM Pools + MHSMRegionsListResult +} + +// ManagedHsmKeysClientCreateIfNotExistResponse contains the response from method ManagedHsmKeysClient.CreateIfNotExist. +type ManagedHsmKeysClientCreateIfNotExistResponse struct { + // The key resource. + ManagedHsmKey +} + +// ManagedHsmKeysClientGetResponse contains the response from method ManagedHsmKeysClient.Get. +type ManagedHsmKeysClientGetResponse struct { + // The key resource. + ManagedHsmKey +} + +// ManagedHsmKeysClientGetVersionResponse contains the response from method ManagedHsmKeysClient.GetVersion. +type ManagedHsmKeysClientGetVersionResponse struct { + // The key resource. + ManagedHsmKey +} + +// ManagedHsmKeysClientListResponse contains the response from method ManagedHsmKeysClient.NewListPager. +type ManagedHsmKeysClientListResponse struct { + // The page of keys. + ManagedHsmKeyListResult +} + +// ManagedHsmKeysClientListVersionsResponse contains the response from method ManagedHsmKeysClient.NewListVersionsPager. +type ManagedHsmKeysClientListVersionsResponse struct { + // The page of keys. + ManagedHsmKeyListResult +} + +// ManagedHsmsClientCheckMhsmNameAvailabilityResponse contains the response from method ManagedHsmsClient.CheckMhsmNameAvailability. +type ManagedHsmsClientCheckMhsmNameAvailabilityResponse struct { + // The CheckMhsmNameAvailability operation response. + CheckMhsmNameAvailabilityResult +} + +// ManagedHsmsClientCreateOrUpdateResponse contains the response from method ManagedHsmsClient.BeginCreateOrUpdate. +type ManagedHsmsClientCreateOrUpdateResponse struct { + // Resource information with extended details. + ManagedHsm +} + +// ManagedHsmsClientDeleteResponse contains the response from method ManagedHsmsClient.BeginDelete. +type ManagedHsmsClientDeleteResponse struct { + // placeholder for future response values +} + +// ManagedHsmsClientGetDeletedResponse contains the response from method ManagedHsmsClient.GetDeleted. +type ManagedHsmsClientGetDeletedResponse struct { + DeletedManagedHsm +} + +// ManagedHsmsClientGetResponse contains the response from method ManagedHsmsClient.Get. +type ManagedHsmsClientGetResponse struct { + // Resource information with extended details. + ManagedHsm +} + +// ManagedHsmsClientListByResourceGroupResponse contains the response from method ManagedHsmsClient.NewListByResourceGroupPager. +type ManagedHsmsClientListByResourceGroupResponse struct { + // List of managed HSM Pools + ManagedHsmListResult +} + +// ManagedHsmsClientListBySubscriptionResponse contains the response from method ManagedHsmsClient.NewListBySubscriptionPager. +type ManagedHsmsClientListBySubscriptionResponse struct { + // List of managed HSM Pools + ManagedHsmListResult +} + +// ManagedHsmsClientListDeletedResponse contains the response from method ManagedHsmsClient.NewListDeletedPager. +type ManagedHsmsClientListDeletedResponse struct { + // List of deleted managed HSM Pools + DeletedManagedHsmListResult +} + +// ManagedHsmsClientPurgeDeletedResponse contains the response from method ManagedHsmsClient.BeginPurgeDeleted. +type ManagedHsmsClientPurgeDeletedResponse struct { + // placeholder for future response values +} + +// ManagedHsmsClientUpdateResponse contains the response from method ManagedHsmsClient.BeginUpdate. +type ManagedHsmsClientUpdateResponse struct { + // Resource information with extended details. + ManagedHsm +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // Result of the request to list Storage operations. It contains a list of operations and a URL link to get the next set of + // results. + OperationListResult +} + +// PrivateEndpointConnectionsClientDeleteResponse contains the response from method PrivateEndpointConnectionsClient.BeginDelete. +type PrivateEndpointConnectionsClientDeleteResponse struct { + // Private endpoint connection resource. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientGetResponse contains the response from method PrivateEndpointConnectionsClient.Get. +type PrivateEndpointConnectionsClientGetResponse struct { + // Private endpoint connection resource. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientListByResourceResponse contains the response from method PrivateEndpointConnectionsClient.NewListByResourcePager. +type PrivateEndpointConnectionsClientListByResourceResponse struct { + // List of private endpoint connections. + PrivateEndpointConnectionListResult +} + +// PrivateEndpointConnectionsClientPutResponse contains the response from method PrivateEndpointConnectionsClient.Put. +type PrivateEndpointConnectionsClientPutResponse struct { + // Private endpoint connection resource. + PrivateEndpointConnection + + // AzureAsyncOperation contains the information returned from the Azure-AsyncOperation header response. + AzureAsyncOperation *string + + // RetryAfter contains the information returned from the Retry-After header response. + RetryAfter *int32 +} + +// PrivateLinkResourcesClientListByVaultResponse contains the response from method PrivateLinkResourcesClient.ListByVault. +type PrivateLinkResourcesClientListByVaultResponse struct { + // A list of private link resources + PrivateLinkResourceListResult +} + +// SecretsClientCreateOrUpdateResponse contains the response from method SecretsClient.CreateOrUpdate. +type SecretsClientCreateOrUpdateResponse struct { + // Resource information with extended details. + Secret +} + +// SecretsClientGetResponse contains the response from method SecretsClient.Get. +type SecretsClientGetResponse struct { + // Resource information with extended details. + Secret +} + +// SecretsClientListResponse contains the response from method SecretsClient.NewListPager. +type SecretsClientListResponse struct { + // List of secrets + SecretListResult +} + +// SecretsClientUpdateResponse contains the response from method SecretsClient.Update. +type SecretsClientUpdateResponse struct { + // Resource information with extended details. + Secret +} + +// VaultsClientCheckNameAvailabilityResponse contains the response from method VaultsClient.CheckNameAvailability. +type VaultsClientCheckNameAvailabilityResponse struct { + // The CheckNameAvailability operation response. + CheckNameAvailabilityResult +} + +// VaultsClientCreateOrUpdateResponse contains the response from method VaultsClient.BeginCreateOrUpdate. +type VaultsClientCreateOrUpdateResponse struct { + // Resource information with extended details. + Vault +} + +// VaultsClientDeleteResponse contains the response from method VaultsClient.Delete. +type VaultsClientDeleteResponse struct { + // placeholder for future response values +} + +// VaultsClientGetDeletedResponse contains the response from method VaultsClient.GetDeleted. +type VaultsClientGetDeletedResponse struct { + // Deleted vault information with extended details. + DeletedVault +} + +// VaultsClientGetResponse contains the response from method VaultsClient.Get. +type VaultsClientGetResponse struct { + // Resource information with extended details. + Vault +} + +// VaultsClientListByResourceGroupResponse contains the response from method VaultsClient.NewListByResourceGroupPager. +type VaultsClientListByResourceGroupResponse struct { + // List of vaults + VaultListResult +} + +// VaultsClientListBySubscriptionResponse contains the response from method VaultsClient.NewListBySubscriptionPager. +type VaultsClientListBySubscriptionResponse struct { + // List of vaults + VaultListResult +} + +// VaultsClientListDeletedResponse contains the response from method VaultsClient.NewListDeletedPager. +type VaultsClientListDeletedResponse struct { + // List of vaults + DeletedVaultListResult +} + +// VaultsClientListResponse contains the response from method VaultsClient.NewListPager. +type VaultsClientListResponse struct { + // List of vault resources. + ResourceListResult +} + +// VaultsClientPurgeDeletedResponse contains the response from method VaultsClient.BeginPurgeDeleted. +type VaultsClientPurgeDeletedResponse struct { + // placeholder for future response values +} + +// VaultsClientUpdateAccessPolicyResponse contains the response from method VaultsClient.UpdateAccessPolicy. +type VaultsClientUpdateAccessPolicyResponse struct { + // Parameters for updating the access policy in a vault + VaultAccessPolicyParameters +} + +// VaultsClientUpdateResponse contains the response from method VaultsClient.Update. +type VaultsClientUpdateResponse struct { + // Resource information with extended details. + Vault +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/secrets_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/secrets_client.go new file mode 100644 index 0000000000..6eb796d08c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/secrets_client.go @@ -0,0 +1,328 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// SecretsClient contains the methods for the Secrets group. +// Don't use this type directly, use NewSecretsClient() instead. +type SecretsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSecretsClient creates a new instance of SecretsClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewSecretsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SecretsClient, error) { + cl, err := arm.NewClient(moduleName+".SecretsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SecretsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update a secret in a key vault in the specified subscription. NOTE: This API is intended for +// internal use in ARM deployments. Users should use the data-plane REST service for interaction +// with vault secrets. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - Name of the vault +// - secretName - Name of the secret. The value you provide may be copied globally for the purpose of running the service. The +// value provided should not include personally identifiable or sensitive information. +// - parameters - Parameters to create or update the secret +// - options - SecretsClientCreateOrUpdateOptions contains the optional parameters for the SecretsClient.CreateOrUpdate method. +func (client *SecretsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vaultName string, secretName string, parameters SecretCreateOrUpdateParameters, options *SecretsClientCreateOrUpdateOptions) (SecretsClientCreateOrUpdateResponse, error) { + var err error + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, vaultName, secretName, parameters, options) + if err != nil { + return SecretsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecretsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SecretsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SecretsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, secretName string, parameters SecretCreateOrUpdateParameters, options *SecretsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if secretName == "" { + return nil, errors.New("parameter secretName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secretName}", url.PathEscape(secretName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *SecretsClient) createOrUpdateHandleResponse(resp *http.Response) (SecretsClientCreateOrUpdateResponse, error) { + result := SecretsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Secret); err != nil { + return SecretsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Get - Gets the specified secret. NOTE: This API is intended for internal use in ARM deployments. Users should use the data-plane +// REST service for interaction with vault secrets. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - The name of the vault. +// - secretName - The name of the secret. +// - options - SecretsClientGetOptions contains the optional parameters for the SecretsClient.Get method. +func (client *SecretsClient) Get(ctx context.Context, resourceGroupName string, vaultName string, secretName string, options *SecretsClientGetOptions) (SecretsClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, vaultName, secretName, options) + if err != nil { + return SecretsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecretsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecretsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SecretsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, secretName string, options *SecretsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if secretName == "" { + return nil, errors.New("parameter secretName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secretName}", url.PathEscape(secretName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SecretsClient) getHandleResponse(resp *http.Response) (SecretsClientGetResponse, error) { + result := SecretsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Secret); err != nil { + return SecretsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - The List operation gets information about the secrets in a vault. NOTE: This API is intended for internal +// use in ARM deployments. Users should use the data-plane REST service for interaction with +// vault secrets. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - The name of the vault. +// - options - SecretsClientListOptions contains the optional parameters for the SecretsClient.NewListPager method. +func (client *SecretsClient) NewListPager(resourceGroupName string, vaultName string, options *SecretsClientListOptions) *runtime.Pager[SecretsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SecretsClientListResponse]{ + More: func(page SecretsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SecretsClientListResponse) (SecretsClientListResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listCreateRequest(ctx, resourceGroupName, vaultName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return SecretsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecretsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SecretsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + }) +} + +// listCreateRequest creates the List request. +func (client *SecretsClient) listCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *SecretsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SecretsClient) listHandleResponse(resp *http.Response) (SecretsClientListResponse, error) { + result := SecretsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretListResult); err != nil { + return SecretsClientListResponse{}, err + } + return result, nil +} + +// Update - Update a secret in the specified subscription. NOTE: This API is intended for internal use in ARM deployments. +// Users should use the data-plane REST service for interaction with vault secrets. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - Name of the vault +// - secretName - Name of the secret +// - parameters - Parameters to patch the secret +// - options - SecretsClientUpdateOptions contains the optional parameters for the SecretsClient.Update method. +func (client *SecretsClient) Update(ctx context.Context, resourceGroupName string, vaultName string, secretName string, parameters SecretPatchParameters, options *SecretsClientUpdateOptions) (SecretsClientUpdateResponse, error) { + var err error + req, err := client.updateCreateRequest(ctx, resourceGroupName, vaultName, secretName, parameters, options) + if err != nil { + return SecretsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecretsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SecretsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *SecretsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, secretName string, parameters SecretPatchParameters, options *SecretsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if secretName == "" { + return nil, errors.New("parameter secretName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secretName}", url.PathEscape(secretName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *SecretsClient) updateHandleResponse(resp *http.Response) (SecretsClientUpdateResponse, error) { + result := SecretsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Secret); err != nil { + return SecretsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_rfc3339.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_rfc3339.go new file mode 100644 index 0000000000..59d8c8054e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_rfc3339.go @@ -0,0 +1,86 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} + +func populateTimeRFC3339(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*timeRFC3339)(t) +} + +func unpopulateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || strings.EqualFold(string(data), "null") { + return nil + } + var aux timeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_unix.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_unix.go new file mode 100644 index 0000000000..bf04637176 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/time_unix.go @@ -0,0 +1,61 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "strings" + "time" +) + +type timeUnix time.Time + +func (t timeUnix) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Time(t).Unix()) +} + +func (t *timeUnix) UnmarshalJSON(data []byte) error { + var seconds int64 + if err := json.Unmarshal(data, &seconds); err != nil { + return err + } + *t = timeUnix(time.Unix(seconds, 0)) + return nil +} + +func (t timeUnix) String() string { + return fmt.Sprintf("%d", time.Time(t).Unix()) +} + +func populateTimeUnix(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*timeUnix)(t) +} + +func unpopulateTimeUnix(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || strings.EqualFold(string(data), "null") { + return nil + } + var aux timeUnix + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/vaults_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/vaults_client.go new file mode 100644 index 0000000000..d791972ced --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault/vaults_client.go @@ -0,0 +1,799 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armkeyvault + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// VaultsClient contains the methods for the Vaults group. +// Don't use this type directly, use NewVaultsClient() instead. +type VaultsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVaultsClient creates a new instance of VaultsClient with the specified values. +// - subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms +// part of the URI for every service call. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewVaultsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VaultsClient, error) { + cl, err := arm.NewClient(moduleName+".VaultsClient", moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VaultsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckNameAvailability - Checks that the vault name is valid and is not already in use. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - vaultName - The name of the vault. +// - options - VaultsClientCheckNameAvailabilityOptions contains the optional parameters for the VaultsClient.CheckNameAvailability +// method. +func (client *VaultsClient) CheckNameAvailability(ctx context.Context, vaultName VaultCheckNameAvailabilityParameters, options *VaultsClientCheckNameAvailabilityOptions) (VaultsClientCheckNameAvailabilityResponse, error) { + var err error + req, err := client.checkNameAvailabilityCreateRequest(ctx, vaultName, options) + if err != nil { + return VaultsClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VaultsClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *VaultsClient) checkNameAvailabilityCreateRequest(ctx context.Context, vaultName VaultCheckNameAvailabilityParameters, options *VaultsClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, vaultName); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *VaultsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (VaultsClientCheckNameAvailabilityResponse, error) { + result := VaultsClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return VaultsClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdate - Create or update a key vault in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the server belongs. +// - vaultName - Name of the vault +// - parameters - Parameters to create or update the vault +// - options - VaultsClientBeginCreateOrUpdateOptions contains the optional parameters for the VaultsClient.BeginCreateOrUpdate +// method. +func (client *VaultsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vaultName string, parameters VaultCreateOrUpdateParameters, options *VaultsClientBeginCreateOrUpdateOptions) (*runtime.Poller[VaultsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vaultName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[VaultsClientCreateOrUpdateResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[VaultsClientCreateOrUpdateResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// CreateOrUpdate - Create or update a key vault in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *VaultsClient) createOrUpdate(ctx context.Context, resourceGroupName string, vaultName string, parameters VaultCreateOrUpdateParameters, options *VaultsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, vaultName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *VaultsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, parameters VaultCreateOrUpdateParameters, options *VaultsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Deletes the specified Azure key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - The name of the vault to delete +// - options - VaultsClientDeleteOptions contains the optional parameters for the VaultsClient.Delete method. +func (client *VaultsClient) Delete(ctx context.Context, resourceGroupName string, vaultName string, options *VaultsClientDeleteOptions) (VaultsClientDeleteResponse, error) { + var err error + req, err := client.deleteCreateRequest(ctx, resourceGroupName, vaultName, options) + if err != nil { + return VaultsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VaultsClientDeleteResponse{}, err + } + return VaultsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *VaultsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *VaultsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified Azure key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - The name of the vault. +// - options - VaultsClientGetOptions contains the optional parameters for the VaultsClient.Get method. +func (client *VaultsClient) Get(ctx context.Context, resourceGroupName string, vaultName string, options *VaultsClientGetOptions) (VaultsClientGetResponse, error) { + var err error + req, err := client.getCreateRequest(ctx, resourceGroupName, vaultName, options) + if err != nil { + return VaultsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VaultsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VaultsClient) getCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, options *VaultsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VaultsClient) getHandleResponse(resp *http.Response) (VaultsClientGetResponse, error) { + result := VaultsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Vault); err != nil { + return VaultsClientGetResponse{}, err + } + return result, nil +} + +// GetDeleted - Gets the deleted Azure key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - vaultName - The name of the vault. +// - location - The location of the deleted vault. +// - options - VaultsClientGetDeletedOptions contains the optional parameters for the VaultsClient.GetDeleted method. +func (client *VaultsClient) GetDeleted(ctx context.Context, vaultName string, location string, options *VaultsClientGetDeletedOptions) (VaultsClientGetDeletedResponse, error) { + var err error + req, err := client.getDeletedCreateRequest(ctx, vaultName, location, options) + if err != nil { + return VaultsClientGetDeletedResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientGetDeletedResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VaultsClientGetDeletedResponse{}, err + } + resp, err := client.getDeletedHandleResponse(httpResp) + return resp, err +} + +// getDeletedCreateRequest creates the GetDeleted request. +func (client *VaultsClient) getDeletedCreateRequest(ctx context.Context, vaultName string, location string, options *VaultsClientGetDeletedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}" + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDeletedHandleResponse handles the GetDeleted response. +func (client *VaultsClient) getDeletedHandleResponse(resp *http.Response) (VaultsClientGetDeletedResponse, error) { + result := VaultsClientGetDeletedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedVault); err != nil { + return VaultsClientGetDeletedResponse{}, err + } + return result, nil +} + +// NewListPager - The List operation gets information about the vaults associated with the subscription. +// +// Generated from API version 2023-07-01 +// - options - VaultsClientListOptions contains the optional parameters for the VaultsClient.NewListPager method. +func (client *VaultsClient) NewListPager(options *VaultsClientListOptions) *runtime.Pager[VaultsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[VaultsClientListResponse]{ + More: func(page VaultsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VaultsClientListResponse) (VaultsClientListResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return VaultsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return VaultsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + }) +} + +// listCreateRequest creates the List request. +func (client *VaultsClient) listCreateRequest(ctx context.Context, options *VaultsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("$filter", "resourceType eq 'Microsoft.KeyVault/vaults'") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2015-11-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *VaultsClient) listHandleResponse(resp *http.Response) (VaultsClientListResponse, error) { + result := VaultsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceListResult); err != nil { + return VaultsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - The List operation gets information about the vaults associated with the subscription and +// within the specified resource group. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - options - VaultsClientListByResourceGroupOptions contains the optional parameters for the VaultsClient.NewListByResourceGroupPager +// method. +func (client *VaultsClient) NewListByResourceGroupPager(resourceGroupName string, options *VaultsClientListByResourceGroupOptions) *runtime.Pager[VaultsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[VaultsClientListByResourceGroupResponse]{ + More: func(page VaultsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VaultsClientListByResourceGroupResponse) (VaultsClientListByResourceGroupResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return VaultsClientListByResourceGroupResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientListByResourceGroupResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return VaultsClientListByResourceGroupResponse{}, runtime.NewResponseError(resp) + } + return client.listByResourceGroupHandleResponse(resp) + }, + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *VaultsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *VaultsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *VaultsClient) listByResourceGroupHandleResponse(resp *http.Response) (VaultsClientListByResourceGroupResponse, error) { + result := VaultsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VaultListResult); err != nil { + return VaultsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - The List operation gets information about the vaults associated with the subscription. +// +// Generated from API version 2023-07-01 +// - options - VaultsClientListBySubscriptionOptions contains the optional parameters for the VaultsClient.NewListBySubscriptionPager +// method. +func (client *VaultsClient) NewListBySubscriptionPager(options *VaultsClientListBySubscriptionOptions) *runtime.Pager[VaultsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[VaultsClientListBySubscriptionResponse]{ + More: func(page VaultsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VaultsClientListBySubscriptionResponse) (VaultsClientListBySubscriptionResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listBySubscriptionCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return VaultsClientListBySubscriptionResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientListBySubscriptionResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return VaultsClientListBySubscriptionResponse{}, runtime.NewResponseError(resp) + } + return client.listBySubscriptionHandleResponse(resp) + }, + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *VaultsClient) listBySubscriptionCreateRequest(ctx context.Context, options *VaultsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/vaults" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *VaultsClient) listBySubscriptionHandleResponse(resp *http.Response) (VaultsClientListBySubscriptionResponse, error) { + result := VaultsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VaultListResult); err != nil { + return VaultsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewListDeletedPager - Gets information about the deleted vaults in a subscription. +// +// Generated from API version 2023-07-01 +// - options - VaultsClientListDeletedOptions contains the optional parameters for the VaultsClient.NewListDeletedPager method. +func (client *VaultsClient) NewListDeletedPager(options *VaultsClientListDeletedOptions) *runtime.Pager[VaultsClientListDeletedResponse] { + return runtime.NewPager(runtime.PagingHandler[VaultsClientListDeletedResponse]{ + More: func(page VaultsClientListDeletedResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VaultsClientListDeletedResponse) (VaultsClientListDeletedResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listDeletedCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return VaultsClientListDeletedResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientListDeletedResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return VaultsClientListDeletedResponse{}, runtime.NewResponseError(resp) + } + return client.listDeletedHandleResponse(resp) + }, + }) +} + +// listDeletedCreateRequest creates the ListDeleted request. +func (client *VaultsClient) listDeletedCreateRequest(ctx context.Context, options *VaultsClientListDeletedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedVaults" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listDeletedHandleResponse handles the ListDeleted response. +func (client *VaultsClient) listDeletedHandleResponse(resp *http.Response) (VaultsClientListDeletedResponse, error) { + result := VaultsClientListDeletedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedVaultListResult); err != nil { + return VaultsClientListDeletedResponse{}, err + } + return result, nil +} + +// BeginPurgeDeleted - Permanently deletes the specified vault. aka Purges the deleted Azure key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - vaultName - The name of the soft-deleted vault. +// - location - The location of the soft-deleted vault. +// - options - VaultsClientBeginPurgeDeletedOptions contains the optional parameters for the VaultsClient.BeginPurgeDeleted +// method. +func (client *VaultsClient) BeginPurgeDeleted(ctx context.Context, vaultName string, location string, options *VaultsClientBeginPurgeDeletedOptions) (*runtime.Poller[VaultsClientPurgeDeletedResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.purgeDeleted(ctx, vaultName, location, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller[VaultsClientPurgeDeletedResponse](resp, client.internal.Pipeline(), nil) + return poller, err + } else { + return runtime.NewPollerFromResumeToken[VaultsClientPurgeDeletedResponse](options.ResumeToken, client.internal.Pipeline(), nil) + } +} + +// PurgeDeleted - Permanently deletes the specified vault. aka Purges the deleted Azure key vault. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +func (client *VaultsClient) purgeDeleted(ctx context.Context, vaultName string, location string, options *VaultsClientBeginPurgeDeletedOptions) (*http.Response, error) { + var err error + req, err := client.purgeDeletedCreateRequest(ctx, vaultName, location, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// purgeDeletedCreateRequest creates the PurgeDeleted request. +func (client *VaultsClient) purgeDeletedCreateRequest(ctx context.Context, vaultName string, location string, options *VaultsClientBeginPurgeDeletedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}/purge" + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Update - Update a key vault in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the server belongs. +// - vaultName - Name of the vault +// - parameters - Parameters to patch the vault +// - options - VaultsClientUpdateOptions contains the optional parameters for the VaultsClient.Update method. +func (client *VaultsClient) Update(ctx context.Context, resourceGroupName string, vaultName string, parameters VaultPatchParameters, options *VaultsClientUpdateOptions) (VaultsClientUpdateResponse, error) { + var err error + req, err := client.updateCreateRequest(ctx, resourceGroupName, vaultName, parameters, options) + if err != nil { + return VaultsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return VaultsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *VaultsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, parameters VaultPatchParameters, options *VaultsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *VaultsClient) updateHandleResponse(resp *http.Response) (VaultsClientUpdateResponse, error) { + result := VaultsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Vault); err != nil { + return VaultsClientUpdateResponse{}, err + } + return result, nil +} + +// UpdateAccessPolicy - Update access policies in a key vault in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-07-01 +// - resourceGroupName - The name of the Resource Group to which the vault belongs. +// - vaultName - Name of the vault +// - operationKind - Name of the operation +// - parameters - Access policy to merge into the vault +// - options - VaultsClientUpdateAccessPolicyOptions contains the optional parameters for the VaultsClient.UpdateAccessPolicy +// method. +func (client *VaultsClient) UpdateAccessPolicy(ctx context.Context, resourceGroupName string, vaultName string, operationKind AccessPolicyUpdateKind, parameters VaultAccessPolicyParameters, options *VaultsClientUpdateAccessPolicyOptions) (VaultsClientUpdateAccessPolicyResponse, error) { + var err error + req, err := client.updateAccessPolicyCreateRequest(ctx, resourceGroupName, vaultName, operationKind, parameters, options) + if err != nil { + return VaultsClientUpdateAccessPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VaultsClientUpdateAccessPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return VaultsClientUpdateAccessPolicyResponse{}, err + } + resp, err := client.updateAccessPolicyHandleResponse(httpResp) + return resp, err +} + +// updateAccessPolicyCreateRequest creates the UpdateAccessPolicy request. +func (client *VaultsClient) updateAccessPolicyCreateRequest(ctx context.Context, resourceGroupName string, vaultName string, operationKind AccessPolicyUpdateKind, parameters VaultAccessPolicyParameters, options *VaultsClientUpdateAccessPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/accessPolicies/{operationKind}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vaultName == "" { + return nil, errors.New("parameter vaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vaultName}", url.PathEscape(vaultName)) + if operationKind == "" { + return nil, errors.New("parameter operationKind cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{operationKind}", url.PathEscape(string(operationKind))) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// updateAccessPolicyHandleResponse handles the UpdateAccessPolicy response. +func (client *VaultsClient) updateAccessPolicyHandleResponse(resp *http.Response) (VaultsClientUpdateAccessPolicyResponse, error) { + result := VaultsClientUpdateAccessPolicyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VaultAccessPolicyParameters); err != nil { + return VaultsClientUpdateAccessPolicyResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/CHANGELOG.md new file mode 100644 index 0000000000..c9aefb3998 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/CHANGELOG.md @@ -0,0 +1,68 @@ +# Release History + +## 1.5.0 (2023-11-24) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + + +## 1.5.0-beta.1 (2023-10-09) +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + +## 1.4.0 (2023-08-25) +### Features Added + +- New value `CorsRuleAllowedMethodsItemCONNECT`, `CorsRuleAllowedMethodsItemTRACE` added to enum type `CorsRuleAllowedMethodsItem` +- New enum type `MigrationName` with values `MigrationNameDefault` +- New enum type `MigrationStatus` with values `MigrationStatusComplete`, `MigrationStatusFailed`, `MigrationStatusInProgress`, `MigrationStatusInvalid`, `MigrationStatusSubmittedForConversion` +- New enum type `PostFailoverRedundancy` with values `PostFailoverRedundancyStandardLRS`, `PostFailoverRedundancyStandardZRS` +- New enum type `PostPlannedFailoverRedundancy` with values `PostPlannedFailoverRedundancyStandardGRS`, `PostPlannedFailoverRedundancyStandardGZRS`, `PostPlannedFailoverRedundancyStandardRAGRS`, `PostPlannedFailoverRedundancyStandardRAGZRS` +- New function `*AccountsClient.BeginCustomerInitiatedMigration(context.Context, string, string, AccountMigration, *AccountsClientBeginCustomerInitiatedMigrationOptions) (*runtime.Poller[AccountsClientCustomerInitiatedMigrationResponse], error)` +- New function `*AccountsClient.GetCustomerInitiatedMigration(context.Context, string, string, MigrationName, *AccountsClientGetCustomerInitiatedMigrationOptions) (AccountsClientGetCustomerInitiatedMigrationResponse, error)` +- New struct `AccountMigration` +- New struct `AccountMigrationProperties` +- New struct `BlobInventoryCreationTime` +- New struct `ErrorAdditionalInfo` +- New struct `ErrorDetail` +- New struct `ErrorResponseAutoGenerated` +- New field `AccountMigrationInProgress`, `IsSKUConversionBlocked` in struct `AccountProperties` +- New field `CreationTime` in struct `BlobInventoryPolicyFilter` +- New field `CanPlannedFailover`, `PostFailoverRedundancy`, `PostPlannedFailoverRedundancy` in struct `GeoReplicationStats` + + +## 1.3.0 (2023-03-27) +### Features Added + +- New struct `ClientFactory` which is a client factory used to create any client in this module + +## 1.2.0 (2022-12-23) +### Features Added + +- New type alias `ListEncryptionScopesInclude` +- New field `FailoverType` in struct `AccountsClientBeginFailoverOptions` +- New field `TierToCold` in struct `ManagementPolicyBaseBlob` +- New field `TierToHot` in struct `ManagementPolicyBaseBlob` +- New field `Filter` in struct `EncryptionScopesClientListOptions` +- New field `Include` in struct `EncryptionScopesClientListOptions` +- New field `Maxpagesize` in struct `EncryptionScopesClientListOptions` +- New field `TierToHot` in struct `ManagementPolicyVersion` +- New field `TierToCold` in struct `ManagementPolicyVersion` +- New field `TierToCold` in struct `ManagementPolicySnapShot` +- New field `TierToHot` in struct `ManagementPolicySnapShot` + + +## 1.1.0 (2022-08-10) +### Features Added + +- New const `DirectoryServiceOptionsAADKERB` + + +## 1.0.0 (2022-05-16) + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html) since version 1.0.0, which contains breaking changes. + +To migrate the existing applications to the latest version, please refer to [Migration Guide](https://aka.ms/azsdk/go/mgmt/migration). + +To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt). \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/LICENSE.txt new file mode 100644 index 0000000000..dc0c2ffb3d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/README.md new file mode 100644 index 0000000000..9f7fe2b72e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/README.md @@ -0,0 +1,102 @@ +# Azure Storage Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage) + +The `armstorage` module provides operations for working with Azure Storage. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/storage/armstorage) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 or above (You could download and install the latest version of Go from [here](https://go.dev/doc/install). It will replace the existing Go on your machine. If you want to install multiple Go versions on the same machine, you could refer this [doc](https://go.dev/doc/manage-install).) + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Storage module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Storage. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Client Factory + +Azure Storage module consists of one or more clients. We provide a client factory which could be used to create any client in this module. + +```go +clientFactory, err := armstorage.NewClientFactory(, cred, nil) +``` + +You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +```go +options := arm.ClientOptions { + ClientOptions: azcore.ClientOptions { + Cloud: cloud.AzureChina, + }, +} +clientFactory, err := armstorage.NewClientFactory(, cred, &options) +``` + +## Clients + +A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. + +```go +client := clientFactory.NewAccountsClient() +``` + +## Fakes + +The fake package contains types used for constructing in-memory fake servers used in unit tests. +This allows writing tests to cover various success/error conditions without the need for connecting to a live service. + +Please see https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/samples/fakes for details and examples on how to use fakes. + +## More sample code + +- [Blob](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/storage/blob) +- [Creating a Fake](https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/resourcemanager/storage/armstorage/fake_example_test.go) +- [File](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/storage/file) +- [Management Policy](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/storage/managementpolicy) +- [Queue](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/storage/queue) +- [Storage Account](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/storage/storageaccount) +- [Table](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/storage/table) + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Storage` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/accounts_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/accounts_client.go new file mode 100644 index 0000000000..81c6bc011d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/accounts_client.go @@ -0,0 +1,1330 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AccountsClient contains the methods for the StorageAccounts group. +// Don't use this type directly, use NewAccountsClient() instead. +type AccountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAccountsClient creates a new instance of AccountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AccountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AccountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAbortHierarchicalNamespaceMigration - Abort live Migration of storage account to enable Hns +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientBeginAbortHierarchicalNamespaceMigrationOptions contains the optional parameters for the AccountsClient.BeginAbortHierarchicalNamespaceMigration +// method. +func (client *AccountsClient) BeginAbortHierarchicalNamespaceMigration(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginAbortHierarchicalNamespaceMigrationOptions) (*runtime.Poller[AccountsClientAbortHierarchicalNamespaceMigrationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.abortHierarchicalNamespaceMigration(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientAbortHierarchicalNamespaceMigrationResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientAbortHierarchicalNamespaceMigrationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AbortHierarchicalNamespaceMigration - Abort live Migration of storage account to enable Hns +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *AccountsClient) abortHierarchicalNamespaceMigration(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginAbortHierarchicalNamespaceMigrationOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginAbortHierarchicalNamespaceMigration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.abortHierarchicalNamespaceMigrationCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// abortHierarchicalNamespaceMigrationCreateRequest creates the AbortHierarchicalNamespaceMigration request. +func (client *AccountsClient) abortHierarchicalNamespaceMigrationCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginAbortHierarchicalNamespaceMigrationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/aborthnsonmigration" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// CheckNameAvailability - Checks that the storage account name is valid and is not already in use. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientCheckNameAvailabilityOptions contains the optional parameters for the AccountsClient.CheckNameAvailability +// method. +func (client *AccountsClient) CheckNameAvailability(ctx context.Context, accountName AccountCheckNameAvailabilityParameters, options *AccountsClientCheckNameAvailabilityOptions) (AccountsClientCheckNameAvailabilityResponse, error) { + var err error + const operationName = "AccountsClient.CheckNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkNameAvailabilityCreateRequest(ctx, accountName, options) + if err != nil { + return AccountsClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *AccountsClient) checkNameAvailabilityCreateRequest(ctx context.Context, accountName AccountCheckNameAvailabilityParameters, options *AccountsClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, accountName); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *AccountsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (AccountsClientCheckNameAvailabilityResponse, error) { + result := AccountsClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return AccountsClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreate - Asynchronously creates a new storage account with the specified parameters. If an account is already created +// and a subsequent create request is issued with different properties, the account properties +// will be updated. If an account is already created and a subsequent create or update request is issued with the exact same +// set of properties, the request will succeed. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The parameters to provide for the created account. +// - options - AccountsClientBeginCreateOptions contains the optional parameters for the AccountsClient.BeginCreate method. +func (client *AccountsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters, options *AccountsClientBeginCreateOptions) (*runtime.Poller[AccountsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Asynchronously creates a new storage account with the specified parameters. If an account is already created and +// a subsequent create request is issued with different properties, the account properties +// will be updated. If an account is already created and a subsequent create or update request is issued with the exact same +// set of properties, the request will succeed. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *AccountsClient) create(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters, options *AccountsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *AccountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters, options *AccountsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginCustomerInitiatedMigration - Account Migration request can be triggered for a storage account to change its redundancy +// level. The migration updates the non-zonal redundant storage account to a zonal redundant account or +// vice-versa in order to have better reliability and availability. Zone-redundant storage (ZRS) replicates your storage account +// synchronously across three Azure availability zones in the primary region. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The request parameters required to perform storage account migration. +// - options - AccountsClientBeginCustomerInitiatedMigrationOptions contains the optional parameters for the AccountsClient.BeginCustomerInitiatedMigration +// method. +func (client *AccountsClient) BeginCustomerInitiatedMigration(ctx context.Context, resourceGroupName string, accountName string, parameters AccountMigration, options *AccountsClientBeginCustomerInitiatedMigrationOptions) (*runtime.Poller[AccountsClientCustomerInitiatedMigrationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.customerInitiatedMigration(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientCustomerInitiatedMigrationResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientCustomerInitiatedMigrationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CustomerInitiatedMigration - Account Migration request can be triggered for a storage account to change its redundancy +// level. The migration updates the non-zonal redundant storage account to a zonal redundant account or +// vice-versa in order to have better reliability and availability. Zone-redundant storage (ZRS) replicates your storage account +// synchronously across three Azure availability zones in the primary region. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *AccountsClient) customerInitiatedMigration(ctx context.Context, resourceGroupName string, accountName string, parameters AccountMigration, options *AccountsClientBeginCustomerInitiatedMigrationOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginCustomerInitiatedMigration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.customerInitiatedMigrationCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// customerInitiatedMigrationCreateRequest creates the CustomerInitiatedMigration request. +func (client *AccountsClient) customerInitiatedMigrationCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters AccountMigration, options *AccountsClientBeginCustomerInitiatedMigrationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/startAccountMigration" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Deletes a storage account in Microsoft Azure. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientDeleteOptions contains the optional parameters for the AccountsClient.Delete method. +func (client *AccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientDeleteOptions) (AccountsClientDeleteResponse, error) { + var err error + const operationName = "AccountsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AccountsClientDeleteResponse{}, err + } + return AccountsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// BeginFailover - A failover request can be triggered for a storage account in the event a primary endpoint becomes unavailable +// for any reason. The failover occurs from the storage account's primary cluster to the +// secondary cluster for RA-GRS accounts. The secondary cluster will become primary after failover and the account is converted +// to LRS. In the case of a Planned Failover, the primary and secondary +// clusters are swapped after failover and the account remains geo-replicated. Failover should continue to be used in the +// event of availability issues as Planned failover is only available while the +// primary and secondary endpoints are available. The primary use case of a Planned Failover is disaster recovery testing +// drills. This type of failover is invoked by setting FailoverType parameter to +// 'Planned'. Learn more about the failover options here- https://learn.microsoft.com/en-us/azure/storage/common/storage-disaster-recovery-guidance +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientBeginFailoverOptions contains the optional parameters for the AccountsClient.BeginFailover method. +func (client *AccountsClient) BeginFailover(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginFailoverOptions) (*runtime.Poller[AccountsClientFailoverResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.failover(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientFailoverResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientFailoverResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Failover - A failover request can be triggered for a storage account in the event a primary endpoint becomes unavailable +// for any reason. The failover occurs from the storage account's primary cluster to the +// secondary cluster for RA-GRS accounts. The secondary cluster will become primary after failover and the account is converted +// to LRS. In the case of a Planned Failover, the primary and secondary +// clusters are swapped after failover and the account remains geo-replicated. Failover should continue to be used in the +// event of availability issues as Planned failover is only available while the +// primary and secondary endpoints are available. The primary use case of a Planned Failover is disaster recovery testing +// drills. This type of failover is invoked by setting FailoverType parameter to +// 'Planned'. Learn more about the failover options here- https://learn.microsoft.com/en-us/azure/storage/common/storage-disaster-recovery-guidance +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *AccountsClient) failover(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginFailoverOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginFailover" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.failoverCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// failoverCreateRequest creates the Failover request. +func (client *AccountsClient) failoverCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginFailoverOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/failover" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.FailoverType != nil { + reqQP.Set("failoverType", "Planned") + } + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// GetCustomerInitiatedMigration - Gets the status of the ongoing migration for the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - migrationName - The name of the Storage Account Migration. It should always be 'default' +// - options - AccountsClientGetCustomerInitiatedMigrationOptions contains the optional parameters for the AccountsClient.GetCustomerInitiatedMigration +// method. +func (client *AccountsClient) GetCustomerInitiatedMigration(ctx context.Context, resourceGroupName string, accountName string, migrationName MigrationName, options *AccountsClientGetCustomerInitiatedMigrationOptions) (AccountsClientGetCustomerInitiatedMigrationResponse, error) { + var err error + const operationName = "AccountsClient.GetCustomerInitiatedMigration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCustomerInitiatedMigrationCreateRequest(ctx, resourceGroupName, accountName, migrationName, options) + if err != nil { + return AccountsClientGetCustomerInitiatedMigrationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientGetCustomerInitiatedMigrationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientGetCustomerInitiatedMigrationResponse{}, err + } + resp, err := client.getCustomerInitiatedMigrationHandleResponse(httpResp) + return resp, err +} + +// getCustomerInitiatedMigrationCreateRequest creates the GetCustomerInitiatedMigration request. +func (client *AccountsClient) getCustomerInitiatedMigrationCreateRequest(ctx context.Context, resourceGroupName string, accountName string, migrationName MigrationName, options *AccountsClientGetCustomerInitiatedMigrationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/accountMigrations/{migrationName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if migrationName == "" { + return nil, errors.New("parameter migrationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{migrationName}", url.PathEscape(string(migrationName))) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getCustomerInitiatedMigrationHandleResponse handles the GetCustomerInitiatedMigration response. +func (client *AccountsClient) getCustomerInitiatedMigrationHandleResponse(resp *http.Response) (AccountsClientGetCustomerInitiatedMigrationResponse, error) { + result := AccountsClientGetCustomerInitiatedMigrationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountMigration); err != nil { + return AccountsClientGetCustomerInitiatedMigrationResponse{}, err + } + return result, nil +} + +// GetProperties - Returns the properties for the specified storage account including but not limited to name, SKU name, location, +// and account status. The ListKeys operation should be used to retrieve storage keys. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientGetPropertiesOptions contains the optional parameters for the AccountsClient.GetProperties method. +func (client *AccountsClient) GetProperties(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientGetPropertiesOptions) (AccountsClientGetPropertiesResponse, error) { + var err error + const operationName = "AccountsClient.GetProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPropertiesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientGetPropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientGetPropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientGetPropertiesResponse{}, err + } + resp, err := client.getPropertiesHandleResponse(httpResp) + return resp, err +} + +// getPropertiesCreateRequest creates the GetProperties request. +func (client *AccountsClient) getPropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientGetPropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getPropertiesHandleResponse handles the GetProperties response. +func (client *AccountsClient) getPropertiesHandleResponse(resp *http.Response) (AccountsClientGetPropertiesResponse, error) { + result := AccountsClientGetPropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return AccountsClientGetPropertiesResponse{}, err + } + return result, nil +} + +// BeginHierarchicalNamespaceMigration - Live Migration of storage account to enable Hns +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - requestType - Required. Hierarchical namespace migration type can either be a hierarchical namespace validation request +// 'HnsOnValidationRequest' or a hydration request 'HnsOnHydrationRequest'. The validation +// request will validate the migration whereas the hydration request will migrate the account. +// - options - AccountsClientBeginHierarchicalNamespaceMigrationOptions contains the optional parameters for the AccountsClient.BeginHierarchicalNamespaceMigration +// method. +func (client *AccountsClient) BeginHierarchicalNamespaceMigration(ctx context.Context, resourceGroupName string, accountName string, requestType string, options *AccountsClientBeginHierarchicalNamespaceMigrationOptions) (*runtime.Poller[AccountsClientHierarchicalNamespaceMigrationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.hierarchicalNamespaceMigration(ctx, resourceGroupName, accountName, requestType, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientHierarchicalNamespaceMigrationResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientHierarchicalNamespaceMigrationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// HierarchicalNamespaceMigration - Live Migration of storage account to enable Hns +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *AccountsClient) hierarchicalNamespaceMigration(ctx context.Context, resourceGroupName string, accountName string, requestType string, options *AccountsClientBeginHierarchicalNamespaceMigrationOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginHierarchicalNamespaceMigration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.hierarchicalNamespaceMigrationCreateRequest(ctx, resourceGroupName, accountName, requestType, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// hierarchicalNamespaceMigrationCreateRequest creates the HierarchicalNamespaceMigration request. +func (client *AccountsClient) hierarchicalNamespaceMigrationCreateRequest(ctx context.Context, resourceGroupName string, accountName string, requestType string, options *AccountsClientBeginHierarchicalNamespaceMigrationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/hnsonmigration" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + reqQP.Set("requestType", requestType) + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListPager - Lists all the storage accounts available under the subscription. Note that storage keys are not returned; +// use the ListKeys operation for this. +// +// Generated from API version 2023-01-01 +// - options - AccountsClientListOptions contains the optional parameters for the AccountsClient.NewListPager method. +func (client *AccountsClient) NewListPager(options *AccountsClientListOptions) *runtime.Pager[AccountsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListResponse]{ + More: func(page AccountsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListResponse) (AccountsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return AccountsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AccountsClient) listCreateRequest(ctx context.Context, options *AccountsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/storageAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountsClient) listHandleResponse(resp *http.Response) (AccountsClientListResponse, error) { + result := AccountsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsClientListResponse{}, err + } + return result, nil +} + +// ListAccountSAS - List SAS credentials of a storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The parameters to provide to list SAS credentials for the storage account. +// - options - AccountsClientListAccountSASOptions contains the optional parameters for the AccountsClient.ListAccountSAS method. +func (client *AccountsClient) ListAccountSAS(ctx context.Context, resourceGroupName string, accountName string, parameters AccountSasParameters, options *AccountsClientListAccountSASOptions) (AccountsClientListAccountSASResponse, error) { + var err error + const operationName = "AccountsClient.ListAccountSAS" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAccountSASCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return AccountsClientListAccountSASResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientListAccountSASResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientListAccountSASResponse{}, err + } + resp, err := client.listAccountSASHandleResponse(httpResp) + return resp, err +} + +// listAccountSASCreateRequest creates the ListAccountSAS request. +func (client *AccountsClient) listAccountSASCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters AccountSasParameters, options *AccountsClientListAccountSASOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListAccountSas" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listAccountSASHandleResponse handles the ListAccountSAS response. +func (client *AccountsClient) listAccountSASHandleResponse(resp *http.Response) (AccountsClientListAccountSASResponse, error) { + result := AccountsClientListAccountSASResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListAccountSasResponse); err != nil { + return AccountsClientListAccountSASResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists all the storage accounts available under the given resource group. Note that storage +// keys are not returned; use the ListKeys operation for this. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - options - AccountsClientListByResourceGroupOptions contains the optional parameters for the AccountsClient.NewListByResourceGroupPager +// method. +func (client *AccountsClient) NewListByResourceGroupPager(resourceGroupName string, options *AccountsClientListByResourceGroupOptions) *runtime.Pager[AccountsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListByResourceGroupResponse]{ + More: func(page AccountsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListByResourceGroupResponse) (AccountsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return AccountsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AccountsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *AccountsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AccountsClient) listByResourceGroupHandleResponse(resp *http.Response) (AccountsClientListByResourceGroupResponse, error) { + result := AccountsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// ListKeys - Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientListKeysOptions contains the optional parameters for the AccountsClient.ListKeys method. +func (client *AccountsClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListKeysOptions) (AccountsClientListKeysResponse, error) { + var err error + const operationName = "AccountsClient.ListKeys" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientListKeysResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientListKeysResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientListKeysResponse{}, err + } + resp, err := client.listKeysHandleResponse(httpResp) + return resp, err +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *AccountsClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Expand != nil { + reqQP.Set("$expand", "kerb") + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *AccountsClient) listKeysHandleResponse(resp *http.Response) (AccountsClientListKeysResponse, error) { + result := AccountsClientListKeysResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListKeysResult); err != nil { + return AccountsClientListKeysResponse{}, err + } + return result, nil +} + +// ListServiceSAS - List service SAS credentials of a specific resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The parameters to provide to list service SAS credentials. +// - options - AccountsClientListServiceSASOptions contains the optional parameters for the AccountsClient.ListServiceSAS method. +func (client *AccountsClient) ListServiceSAS(ctx context.Context, resourceGroupName string, accountName string, parameters ServiceSasParameters, options *AccountsClientListServiceSASOptions) (AccountsClientListServiceSASResponse, error) { + var err error + const operationName = "AccountsClient.ListServiceSAS" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listServiceSASCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return AccountsClientListServiceSASResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientListServiceSASResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientListServiceSASResponse{}, err + } + resp, err := client.listServiceSASHandleResponse(httpResp) + return resp, err +} + +// listServiceSASCreateRequest creates the ListServiceSAS request. +func (client *AccountsClient) listServiceSASCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters ServiceSasParameters, options *AccountsClientListServiceSASOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListServiceSas" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// listServiceSASHandleResponse handles the ListServiceSAS response. +func (client *AccountsClient) listServiceSASHandleResponse(resp *http.Response) (AccountsClientListServiceSASResponse, error) { + result := AccountsClientListServiceSASResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListServiceSasResponse); err != nil { + return AccountsClientListServiceSASResponse{}, err + } + return result, nil +} + +// RegenerateKey - Regenerates one of the access keys or Kerberos keys for the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - regenerateKey - Specifies name of the key which should be regenerated -- key1, key2, kerb1, kerb2. +// - options - AccountsClientRegenerateKeyOptions contains the optional parameters for the AccountsClient.RegenerateKey method. +func (client *AccountsClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, regenerateKey AccountRegenerateKeyParameters, options *AccountsClientRegenerateKeyOptions) (AccountsClientRegenerateKeyResponse, error) { + var err error + const operationName = "AccountsClient.RegenerateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.regenerateKeyCreateRequest(ctx, resourceGroupName, accountName, regenerateKey, options) + if err != nil { + return AccountsClientRegenerateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientRegenerateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientRegenerateKeyResponse{}, err + } + resp, err := client.regenerateKeyHandleResponse(httpResp) + return resp, err +} + +// regenerateKeyCreateRequest creates the RegenerateKey request. +func (client *AccountsClient) regenerateKeyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, regenerateKey AccountRegenerateKeyParameters, options *AccountsClientRegenerateKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, regenerateKey); err != nil { + return nil, err + } + return req, nil +} + +// regenerateKeyHandleResponse handles the RegenerateKey response. +func (client *AccountsClient) regenerateKeyHandleResponse(resp *http.Response) (AccountsClientRegenerateKeyResponse, error) { + result := AccountsClientRegenerateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListKeysResult); err != nil { + return AccountsClientRegenerateKeyResponse{}, err + } + return result, nil +} + +// BeginRestoreBlobRanges - Restore blobs in the specified blob ranges +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The parameters to provide for restore blob ranges. +// - options - AccountsClientBeginRestoreBlobRangesOptions contains the optional parameters for the AccountsClient.BeginRestoreBlobRanges +// method. +func (client *AccountsClient) BeginRestoreBlobRanges(ctx context.Context, resourceGroupName string, accountName string, parameters BlobRestoreParameters, options *AccountsClientBeginRestoreBlobRangesOptions) (*runtime.Poller[AccountsClientRestoreBlobRangesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restoreBlobRanges(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientRestoreBlobRangesResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientRestoreBlobRangesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RestoreBlobRanges - Restore blobs in the specified blob ranges +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *AccountsClient) restoreBlobRanges(ctx context.Context, resourceGroupName string, accountName string, parameters BlobRestoreParameters, options *AccountsClientBeginRestoreBlobRangesOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginRestoreBlobRanges" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restoreBlobRangesCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// restoreBlobRangesCreateRequest creates the RestoreBlobRanges request. +func (client *AccountsClient) restoreBlobRangesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters BlobRestoreParameters, options *AccountsClientBeginRestoreBlobRangesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/restoreBlobRanges" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// RevokeUserDelegationKeys - Revoke user delegation keys. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - AccountsClientRevokeUserDelegationKeysOptions contains the optional parameters for the AccountsClient.RevokeUserDelegationKeys +// method. +func (client *AccountsClient) RevokeUserDelegationKeys(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientRevokeUserDelegationKeysOptions) (AccountsClientRevokeUserDelegationKeysResponse, error) { + var err error + const operationName = "AccountsClient.RevokeUserDelegationKeys" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.revokeUserDelegationKeysCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientRevokeUserDelegationKeysResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientRevokeUserDelegationKeysResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientRevokeUserDelegationKeysResponse{}, err + } + return AccountsClientRevokeUserDelegationKeysResponse{}, nil +} + +// revokeUserDelegationKeysCreateRequest creates the RevokeUserDelegationKeys request. +func (client *AccountsClient) revokeUserDelegationKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientRevokeUserDelegationKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/revokeUserDelegationKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Update - The update operation can be used to update the SKU, encryption, access tier, or tags for a storage account. It +// can also be used to map the account to a custom domain. Only one custom domain is +// supported per storage account; the replacement/change of custom domain is not supported. In order to replace an old custom +// domain, the old value must be cleared/unregistered before a new value can be +// set. The update of multiple properties is supported. This call does not change the storage keys for the account. If you +// want to change the storage account keys, use the regenerate keys operation. The +// location and name of the storage account cannot be changed after creation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The parameters to provide for the updated account. +// - options - AccountsClientUpdateOptions contains the optional parameters for the AccountsClient.Update method. +func (client *AccountsClient) Update(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters, options *AccountsClientUpdateOptions) (AccountsClientUpdateResponse, error) { + var err error + const operationName = "AccountsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return AccountsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *AccountsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters, options *AccountsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *AccountsClient) updateHandleResponse(resp *http.Response) (AccountsClientUpdateResponse, error) { + result := AccountsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return AccountsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/assets.json new file mode 100644 index 0000000000..799f7afd7f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "go", + "TagPrefix": "go/resourcemanager/storage/armstorage", + "Tag": "go/resourcemanager/storage/armstorage_c9d59e874d" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/autorest.md new file mode 100644 index 0000000000..2a581188e6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/autorest.md @@ -0,0 +1,15 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/0baf811c3c76c87b3c127d098519bd97141222dd/specification/storage/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/0baf811c3c76c87b3c127d098519bd97141222dd/specification/storage/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 1.5.0 +modelerfour: + seal-single-value-enum-by-default: true +tag: package-2023-01 +``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobcontainers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobcontainers_client.go new file mode 100644 index 0000000000..666afdcd8d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobcontainers_client.go @@ -0,0 +1,1151 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// BlobContainersClient contains the methods for the BlobContainers group. +// Don't use this type directly, use NewBlobContainersClient() instead. +type BlobContainersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBlobContainersClient creates a new instance of BlobContainersClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewBlobContainersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BlobContainersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BlobContainersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// ClearLegalHold - Clears legal hold tags. Clearing the same or non-existent tag results in an idempotent operation. ClearLegalHold +// clears out only the specified tags in the request. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - legalHold - The LegalHold property that will be clear from a blob container. +// - options - BlobContainersClientClearLegalHoldOptions contains the optional parameters for the BlobContainersClient.ClearLegalHold +// method. +func (client *BlobContainersClient) ClearLegalHold(ctx context.Context, resourceGroupName string, accountName string, containerName string, legalHold LegalHold, options *BlobContainersClientClearLegalHoldOptions) (BlobContainersClientClearLegalHoldResponse, error) { + var err error + const operationName = "BlobContainersClient.ClearLegalHold" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.clearLegalHoldCreateRequest(ctx, resourceGroupName, accountName, containerName, legalHold, options) + if err != nil { + return BlobContainersClientClearLegalHoldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientClearLegalHoldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientClearLegalHoldResponse{}, err + } + resp, err := client.clearLegalHoldHandleResponse(httpResp) + return resp, err +} + +// clearLegalHoldCreateRequest creates the ClearLegalHold request. +func (client *BlobContainersClient) clearLegalHoldCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, legalHold LegalHold, options *BlobContainersClientClearLegalHoldOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/clearLegalHold" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, legalHold); err != nil { + return nil, err + } + return req, nil +} + +// clearLegalHoldHandleResponse handles the ClearLegalHold response. +func (client *BlobContainersClient) clearLegalHoldHandleResponse(resp *http.Response) (BlobContainersClientClearLegalHoldResponse, error) { + result := BlobContainersClientClearLegalHoldResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LegalHold); err != nil { + return BlobContainersClientClearLegalHoldResponse{}, err + } + return result, nil +} + +// Create - Creates a new container under the specified account as described by request body. The container resource includes +// metadata and properties for that container. It does not include a list of the blobs +// contained by the container. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - blobContainer - Properties of the blob container to create. +// - options - BlobContainersClientCreateOptions contains the optional parameters for the BlobContainersClient.Create method. +func (client *BlobContainersClient) Create(ctx context.Context, resourceGroupName string, accountName string, containerName string, blobContainer BlobContainer, options *BlobContainersClientCreateOptions) (BlobContainersClientCreateResponse, error) { + var err error + const operationName = "BlobContainersClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, containerName, blobContainer, options) + if err != nil { + return BlobContainersClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *BlobContainersClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, blobContainer BlobContainer, options *BlobContainersClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, blobContainer); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *BlobContainersClient) createHandleResponse(resp *http.Response) (BlobContainersClientCreateResponse, error) { + result := BlobContainersClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobContainer); err != nil { + return BlobContainersClientCreateResponse{}, err + } + return result, nil +} + +// CreateOrUpdateImmutabilityPolicy - Creates or updates an unlocked immutability policy. ETag in If-Match is honored if given +// but not required for this operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - BlobContainersClientCreateOrUpdateImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.CreateOrUpdateImmutabilityPolicy +// method. +func (client *BlobContainersClient) CreateOrUpdateImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientCreateOrUpdateImmutabilityPolicyOptions) (BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse, error) { + var err error + const operationName = "BlobContainersClient.CreateOrUpdateImmutabilityPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateImmutabilityPolicyCreateRequest(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse{}, err + } + resp, err := client.createOrUpdateImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateImmutabilityPolicyCreateRequest creates the CreateOrUpdateImmutabilityPolicy request. +func (client *BlobContainersClient) createOrUpdateImmutabilityPolicyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientCreateOrUpdateImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/immutabilityPolicies/{immutabilityPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + urlPath = strings.ReplaceAll(urlPath, "{immutabilityPolicyName}", url.PathEscape("default")) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Parameters != nil { + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// createOrUpdateImmutabilityPolicyHandleResponse handles the CreateOrUpdateImmutabilityPolicy response. +func (client *BlobContainersClient) createOrUpdateImmutabilityPolicyHandleResponse(resp *http.Response) (BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse, error) { + result := BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ImmutabilityPolicy); err != nil { + return BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified container under its account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - BlobContainersClientDeleteOptions contains the optional parameters for the BlobContainersClient.Delete method. +func (client *BlobContainersClient) Delete(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientDeleteOptions) (BlobContainersClientDeleteResponse, error) { + var err error + const operationName = "BlobContainersClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return BlobContainersClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientDeleteResponse{}, err + } + return BlobContainersClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *BlobContainersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// DeleteImmutabilityPolicy - Aborts an unlocked immutability policy. The response of delete has immutabilityPeriodSinceCreationInDays +// set to 0. ETag in If-Match is required for this operation. Deleting a locked immutability +// policy is not allowed, the only way is to delete the container after deleting all expired blobs inside the policy locked +// container. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - ifMatch - The entity state (ETag) version of the immutability policy to update. A value of "*" can be used to apply the +// operation only if the immutability policy already exists. If omitted, this operation will +// always be applied. +// - options - BlobContainersClientDeleteImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.DeleteImmutabilityPolicy +// method. +func (client *BlobContainersClient) DeleteImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, options *BlobContainersClientDeleteImmutabilityPolicyOptions) (BlobContainersClientDeleteImmutabilityPolicyResponse, error) { + var err error + const operationName = "BlobContainersClient.DeleteImmutabilityPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteImmutabilityPolicyCreateRequest(ctx, resourceGroupName, accountName, containerName, ifMatch, options) + if err != nil { + return BlobContainersClientDeleteImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientDeleteImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientDeleteImmutabilityPolicyResponse{}, err + } + resp, err := client.deleteImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// deleteImmutabilityPolicyCreateRequest creates the DeleteImmutabilityPolicy request. +func (client *BlobContainersClient) deleteImmutabilityPolicyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, options *BlobContainersClientDeleteImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/immutabilityPolicies/{immutabilityPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + urlPath = strings.ReplaceAll(urlPath, "{immutabilityPolicyName}", url.PathEscape("default")) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["If-Match"] = []string{ifMatch} + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// deleteImmutabilityPolicyHandleResponse handles the DeleteImmutabilityPolicy response. +func (client *BlobContainersClient) deleteImmutabilityPolicyHandleResponse(resp *http.Response) (BlobContainersClientDeleteImmutabilityPolicyResponse, error) { + result := BlobContainersClientDeleteImmutabilityPolicyResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ImmutabilityPolicy); err != nil { + return BlobContainersClientDeleteImmutabilityPolicyResponse{}, err + } + return result, nil +} + +// ExtendImmutabilityPolicy - Extends the immutabilityPeriodSinceCreationInDays of a locked immutabilityPolicy. The only action +// allowed on a Locked policy will be this action. ETag in If-Match is required for this operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - ifMatch - The entity state (ETag) version of the immutability policy to update. A value of "*" can be used to apply the +// operation only if the immutability policy already exists. If omitted, this operation will +// always be applied. +// - options - BlobContainersClientExtendImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.ExtendImmutabilityPolicy +// method. +func (client *BlobContainersClient) ExtendImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, options *BlobContainersClientExtendImmutabilityPolicyOptions) (BlobContainersClientExtendImmutabilityPolicyResponse, error) { + var err error + const operationName = "BlobContainersClient.ExtendImmutabilityPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.extendImmutabilityPolicyCreateRequest(ctx, resourceGroupName, accountName, containerName, ifMatch, options) + if err != nil { + return BlobContainersClientExtendImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientExtendImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientExtendImmutabilityPolicyResponse{}, err + } + resp, err := client.extendImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// extendImmutabilityPolicyCreateRequest creates the ExtendImmutabilityPolicy request. +func (client *BlobContainersClient) extendImmutabilityPolicyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, options *BlobContainersClientExtendImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/immutabilityPolicies/default/extend" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["If-Match"] = []string{ifMatch} + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Parameters != nil { + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// extendImmutabilityPolicyHandleResponse handles the ExtendImmutabilityPolicy response. +func (client *BlobContainersClient) extendImmutabilityPolicyHandleResponse(resp *http.Response) (BlobContainersClientExtendImmutabilityPolicyResponse, error) { + result := BlobContainersClientExtendImmutabilityPolicyResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ImmutabilityPolicy); err != nil { + return BlobContainersClientExtendImmutabilityPolicyResponse{}, err + } + return result, nil +} + +// Get - Gets properties of a specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - BlobContainersClientGetOptions contains the optional parameters for the BlobContainersClient.Get method. +func (client *BlobContainersClient) Get(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientGetOptions) (BlobContainersClientGetResponse, error) { + var err error + const operationName = "BlobContainersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return BlobContainersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BlobContainersClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BlobContainersClient) getHandleResponse(resp *http.Response) (BlobContainersClientGetResponse, error) { + result := BlobContainersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobContainer); err != nil { + return BlobContainersClientGetResponse{}, err + } + return result, nil +} + +// GetImmutabilityPolicy - Gets the existing immutability policy along with the corresponding ETag in response headers and +// body. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - BlobContainersClientGetImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.GetImmutabilityPolicy +// method. +func (client *BlobContainersClient) GetImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientGetImmutabilityPolicyOptions) (BlobContainersClientGetImmutabilityPolicyResponse, error) { + var err error + const operationName = "BlobContainersClient.GetImmutabilityPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getImmutabilityPolicyCreateRequest(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return BlobContainersClientGetImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientGetImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientGetImmutabilityPolicyResponse{}, err + } + resp, err := client.getImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// getImmutabilityPolicyCreateRequest creates the GetImmutabilityPolicy request. +func (client *BlobContainersClient) getImmutabilityPolicyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientGetImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/immutabilityPolicies/{immutabilityPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + urlPath = strings.ReplaceAll(urlPath, "{immutabilityPolicyName}", url.PathEscape("default")) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getImmutabilityPolicyHandleResponse handles the GetImmutabilityPolicy response. +func (client *BlobContainersClient) getImmutabilityPolicyHandleResponse(resp *http.Response) (BlobContainersClientGetImmutabilityPolicyResponse, error) { + result := BlobContainersClientGetImmutabilityPolicyResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ImmutabilityPolicy); err != nil { + return BlobContainersClientGetImmutabilityPolicyResponse{}, err + } + return result, nil +} + +// Lease - The Lease Container operation establishes and manages a lock on a container for delete operations. The lock duration +// can be 15 to 60 seconds, or can be infinite. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - BlobContainersClientLeaseOptions contains the optional parameters for the BlobContainersClient.Lease method. +func (client *BlobContainersClient) Lease(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientLeaseOptions) (BlobContainersClientLeaseResponse, error) { + var err error + const operationName = "BlobContainersClient.Lease" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.leaseCreateRequest(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return BlobContainersClientLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientLeaseResponse{}, err + } + resp, err := client.leaseHandleResponse(httpResp) + return resp, err +} + +// leaseCreateRequest creates the Lease request. +func (client *BlobContainersClient) leaseCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientLeaseOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/lease" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Parameters != nil { + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// leaseHandleResponse handles the Lease response. +func (client *BlobContainersClient) leaseHandleResponse(resp *http.Response) (BlobContainersClientLeaseResponse, error) { + result := BlobContainersClientLeaseResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LeaseContainerResponse); err != nil { + return BlobContainersClientLeaseResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all containers and does not support a prefix like data plane. Also SRP today does not return continuation +// token. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - BlobContainersClientListOptions contains the optional parameters for the BlobContainersClient.NewListPager method. +func (client *BlobContainersClient) NewListPager(resourceGroupName string, accountName string, options *BlobContainersClientListOptions) *runtime.Pager[BlobContainersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BlobContainersClientListResponse]{ + More: func(page BlobContainersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BlobContainersClientListResponse) (BlobContainersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BlobContainersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return BlobContainersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BlobContainersClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *BlobContainersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Maxpagesize != nil { + reqQP.Set("$maxpagesize", *options.Maxpagesize) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Include != nil { + reqQP.Set("$include", string(*options.Include)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BlobContainersClient) listHandleResponse(resp *http.Response) (BlobContainersClientListResponse, error) { + result := BlobContainersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListContainerItems); err != nil { + return BlobContainersClientListResponse{}, err + } + return result, nil +} + +// LockImmutabilityPolicy - Sets the ImmutabilityPolicy to Locked state. The only action allowed on a Locked policy is ExtendImmutabilityPolicy +// action. ETag in If-Match is required for this operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - ifMatch - The entity state (ETag) version of the immutability policy to update. A value of "*" can be used to apply the +// operation only if the immutability policy already exists. If omitted, this operation will +// always be applied. +// - options - BlobContainersClientLockImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.LockImmutabilityPolicy +// method. +func (client *BlobContainersClient) LockImmutabilityPolicy(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, options *BlobContainersClientLockImmutabilityPolicyOptions) (BlobContainersClientLockImmutabilityPolicyResponse, error) { + var err error + const operationName = "BlobContainersClient.LockImmutabilityPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.lockImmutabilityPolicyCreateRequest(ctx, resourceGroupName, accountName, containerName, ifMatch, options) + if err != nil { + return BlobContainersClientLockImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientLockImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientLockImmutabilityPolicyResponse{}, err + } + resp, err := client.lockImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// lockImmutabilityPolicyCreateRequest creates the LockImmutabilityPolicy request. +func (client *BlobContainersClient) lockImmutabilityPolicyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, ifMatch string, options *BlobContainersClientLockImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/immutabilityPolicies/default/lock" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["If-Match"] = []string{ifMatch} + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// lockImmutabilityPolicyHandleResponse handles the LockImmutabilityPolicy response. +func (client *BlobContainersClient) lockImmutabilityPolicyHandleResponse(resp *http.Response) (BlobContainersClientLockImmutabilityPolicyResponse, error) { + result := BlobContainersClientLockImmutabilityPolicyResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ImmutabilityPolicy); err != nil { + return BlobContainersClientLockImmutabilityPolicyResponse{}, err + } + return result, nil +} + +// BeginObjectLevelWorm - This operation migrates a blob container from container level WORM to object level immutability +// enabled container. Prerequisites require a container level immutability policy either in locked or +// unlocked state, Account level versioning must be enabled and there should be no Legal hold on the container. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - BlobContainersClientBeginObjectLevelWormOptions contains the optional parameters for the BlobContainersClient.BeginObjectLevelWorm +// method. +func (client *BlobContainersClient) BeginObjectLevelWorm(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientBeginObjectLevelWormOptions) (*runtime.Poller[BlobContainersClientObjectLevelWormResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.objectLevelWorm(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BlobContainersClientObjectLevelWormResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BlobContainersClientObjectLevelWormResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ObjectLevelWorm - This operation migrates a blob container from container level WORM to object level immutability enabled +// container. Prerequisites require a container level immutability policy either in locked or +// unlocked state, Account level versioning must be enabled and there should be no Legal hold on the container. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +func (client *BlobContainersClient) objectLevelWorm(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientBeginObjectLevelWormOptions) (*http.Response, error) { + var err error + const operationName = "BlobContainersClient.BeginObjectLevelWorm" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.objectLevelWormCreateRequest(ctx, resourceGroupName, accountName, containerName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// objectLevelWormCreateRequest creates the ObjectLevelWorm request. +func (client *BlobContainersClient) objectLevelWormCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, options *BlobContainersClientBeginObjectLevelWormOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/migrate" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// SetLegalHold - Sets legal hold tags. Setting the same tag results in an idempotent operation. SetLegalHold follows an append +// pattern and does not clear out the existing tags that are not specified in the request. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - legalHold - The LegalHold property that will be set to a blob container. +// - options - BlobContainersClientSetLegalHoldOptions contains the optional parameters for the BlobContainersClient.SetLegalHold +// method. +func (client *BlobContainersClient) SetLegalHold(ctx context.Context, resourceGroupName string, accountName string, containerName string, legalHold LegalHold, options *BlobContainersClientSetLegalHoldOptions) (BlobContainersClientSetLegalHoldResponse, error) { + var err error + const operationName = "BlobContainersClient.SetLegalHold" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setLegalHoldCreateRequest(ctx, resourceGroupName, accountName, containerName, legalHold, options) + if err != nil { + return BlobContainersClientSetLegalHoldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientSetLegalHoldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientSetLegalHoldResponse{}, err + } + resp, err := client.setLegalHoldHandleResponse(httpResp) + return resp, err +} + +// setLegalHoldCreateRequest creates the SetLegalHold request. +func (client *BlobContainersClient) setLegalHoldCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, legalHold LegalHold, options *BlobContainersClientSetLegalHoldOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/setLegalHold" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, legalHold); err != nil { + return nil, err + } + return req, nil +} + +// setLegalHoldHandleResponse handles the SetLegalHold response. +func (client *BlobContainersClient) setLegalHoldHandleResponse(resp *http.Response) (BlobContainersClientSetLegalHoldResponse, error) { + result := BlobContainersClientSetLegalHoldResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LegalHold); err != nil { + return BlobContainersClientSetLegalHoldResponse{}, err + } + return result, nil +} + +// Update - Updates container properties as specified in request body. Properties not mentioned in the request will be unchanged. +// Update fails if the specified container doesn't already exist. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - containerName - The name of the blob container within the specified storage account. Blob container names must be between +// 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - blobContainer - Properties to update for the blob container. +// - options - BlobContainersClientUpdateOptions contains the optional parameters for the BlobContainersClient.Update method. +func (client *BlobContainersClient) Update(ctx context.Context, resourceGroupName string, accountName string, containerName string, blobContainer BlobContainer, options *BlobContainersClientUpdateOptions) (BlobContainersClientUpdateResponse, error) { + var err error + const operationName = "BlobContainersClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, containerName, blobContainer, options) + if err != nil { + return BlobContainersClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobContainersClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobContainersClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *BlobContainersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, containerName string, blobContainer BlobContainer, options *BlobContainersClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, blobContainer); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *BlobContainersClient) updateHandleResponse(resp *http.Response) (BlobContainersClientUpdateResponse, error) { + result := BlobContainersClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobContainer); err != nil { + return BlobContainersClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobinventorypolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobinventorypolicies_client.go new file mode 100644 index 0000000000..5fd736aae7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobinventorypolicies_client.go @@ -0,0 +1,318 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// BlobInventoryPoliciesClient contains the methods for the BlobInventoryPolicies group. +// Don't use this type directly, use NewBlobInventoryPoliciesClient() instead. +type BlobInventoryPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBlobInventoryPoliciesClient creates a new instance of BlobInventoryPoliciesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewBlobInventoryPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BlobInventoryPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BlobInventoryPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Sets the blob inventory policy to the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - blobInventoryPolicyName - The name of the storage account blob inventory policy. It should always be 'default' +// - properties - The blob inventory policy set to a storage account. +// - options - BlobInventoryPoliciesClientCreateOrUpdateOptions contains the optional parameters for the BlobInventoryPoliciesClient.CreateOrUpdate +// method. +func (client *BlobInventoryPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, blobInventoryPolicyName BlobInventoryPolicyName, properties BlobInventoryPolicy, options *BlobInventoryPoliciesClientCreateOrUpdateOptions) (BlobInventoryPoliciesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "BlobInventoryPoliciesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, blobInventoryPolicyName, properties, options) + if err != nil { + return BlobInventoryPoliciesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobInventoryPoliciesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobInventoryPoliciesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *BlobInventoryPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, blobInventoryPolicyName BlobInventoryPolicyName, properties BlobInventoryPolicy, options *BlobInventoryPoliciesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/inventoryPolicies/{blobInventoryPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if blobInventoryPolicyName == "" { + return nil, errors.New("parameter blobInventoryPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobInventoryPolicyName}", url.PathEscape(string(blobInventoryPolicyName))) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *BlobInventoryPoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (BlobInventoryPoliciesClientCreateOrUpdateResponse, error) { + result := BlobInventoryPoliciesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobInventoryPolicy); err != nil { + return BlobInventoryPoliciesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the blob inventory policy associated with the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - blobInventoryPolicyName - The name of the storage account blob inventory policy. It should always be 'default' +// - options - BlobInventoryPoliciesClientDeleteOptions contains the optional parameters for the BlobInventoryPoliciesClient.Delete +// method. +func (client *BlobInventoryPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, blobInventoryPolicyName BlobInventoryPolicyName, options *BlobInventoryPoliciesClientDeleteOptions) (BlobInventoryPoliciesClientDeleteResponse, error) { + var err error + const operationName = "BlobInventoryPoliciesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, blobInventoryPolicyName, options) + if err != nil { + return BlobInventoryPoliciesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobInventoryPoliciesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BlobInventoryPoliciesClientDeleteResponse{}, err + } + return BlobInventoryPoliciesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *BlobInventoryPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, blobInventoryPolicyName BlobInventoryPolicyName, options *BlobInventoryPoliciesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/inventoryPolicies/{blobInventoryPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if blobInventoryPolicyName == "" { + return nil, errors.New("parameter blobInventoryPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobInventoryPolicyName}", url.PathEscape(string(blobInventoryPolicyName))) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the blob inventory policy associated with the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - blobInventoryPolicyName - The name of the storage account blob inventory policy. It should always be 'default' +// - options - BlobInventoryPoliciesClientGetOptions contains the optional parameters for the BlobInventoryPoliciesClient.Get +// method. +func (client *BlobInventoryPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, blobInventoryPolicyName BlobInventoryPolicyName, options *BlobInventoryPoliciesClientGetOptions) (BlobInventoryPoliciesClientGetResponse, error) { + var err error + const operationName = "BlobInventoryPoliciesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, blobInventoryPolicyName, options) + if err != nil { + return BlobInventoryPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobInventoryPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobInventoryPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BlobInventoryPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, blobInventoryPolicyName BlobInventoryPolicyName, options *BlobInventoryPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/inventoryPolicies/{blobInventoryPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if blobInventoryPolicyName == "" { + return nil, errors.New("parameter blobInventoryPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobInventoryPolicyName}", url.PathEscape(string(blobInventoryPolicyName))) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BlobInventoryPoliciesClient) getHandleResponse(resp *http.Response) (BlobInventoryPoliciesClientGetResponse, error) { + result := BlobInventoryPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobInventoryPolicy); err != nil { + return BlobInventoryPoliciesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the blob inventory policy associated with the specified storage account. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - BlobInventoryPoliciesClientListOptions contains the optional parameters for the BlobInventoryPoliciesClient.NewListPager +// method. +func (client *BlobInventoryPoliciesClient) NewListPager(resourceGroupName string, accountName string, options *BlobInventoryPoliciesClientListOptions) *runtime.Pager[BlobInventoryPoliciesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BlobInventoryPoliciesClientListResponse]{ + More: func(page BlobInventoryPoliciesClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *BlobInventoryPoliciesClientListResponse) (BlobInventoryPoliciesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BlobInventoryPoliciesClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return BlobInventoryPoliciesClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobInventoryPoliciesClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return BlobInventoryPoliciesClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BlobInventoryPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *BlobInventoryPoliciesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/inventoryPolicies" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BlobInventoryPoliciesClient) listHandleResponse(resp *http.Response) (BlobInventoryPoliciesClientListResponse, error) { + result := BlobInventoryPoliciesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListBlobInventoryPolicy); err != nil { + return BlobInventoryPoliciesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobservices_client.go new file mode 100644 index 0000000000..18122f9254 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/blobservices_client.go @@ -0,0 +1,251 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// BlobServicesClient contains the methods for the BlobServices group. +// Don't use this type directly, use NewBlobServicesClient() instead. +type BlobServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBlobServicesClient creates a new instance of BlobServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewBlobServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BlobServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BlobServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetServiceProperties - Gets the properties of a storage account’s Blob service, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - BlobServicesClientGetServicePropertiesOptions contains the optional parameters for the BlobServicesClient.GetServiceProperties +// method. +func (client *BlobServicesClient) GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, options *BlobServicesClientGetServicePropertiesOptions) (BlobServicesClientGetServicePropertiesResponse, error) { + var err error + const operationName = "BlobServicesClient.GetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return BlobServicesClientGetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobServicesClientGetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobServicesClientGetServicePropertiesResponse{}, err + } + resp, err := client.getServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// getServicePropertiesCreateRequest creates the GetServiceProperties request. +func (client *BlobServicesClient) getServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *BlobServicesClientGetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/{BlobServicesName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{BlobServicesName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getServicePropertiesHandleResponse handles the GetServiceProperties response. +func (client *BlobServicesClient) getServicePropertiesHandleResponse(resp *http.Response) (BlobServicesClientGetServicePropertiesResponse, error) { + result := BlobServicesClientGetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobServiceProperties); err != nil { + return BlobServicesClientGetServicePropertiesResponse{}, err + } + return result, nil +} + +// NewListPager - List blob services of storage account. It returns a collection of one object named default. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - BlobServicesClientListOptions contains the optional parameters for the BlobServicesClient.NewListPager method. +func (client *BlobServicesClient) NewListPager(resourceGroupName string, accountName string, options *BlobServicesClientListOptions) *runtime.Pager[BlobServicesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BlobServicesClientListResponse]{ + More: func(page BlobServicesClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *BlobServicesClientListResponse) (BlobServicesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BlobServicesClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return BlobServicesClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobServicesClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return BlobServicesClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BlobServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *BlobServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BlobServicesClient) listHandleResponse(resp *http.Response) (BlobServicesClientListResponse, error) { + result := BlobServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobServiceItems); err != nil { + return BlobServicesClientListResponse{}, err + } + return result, nil +} + +// SetServiceProperties - Sets the properties of a storage account’s Blob service, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The properties of a storage account’s Blob service, including properties for Storage Analytics and CORS (Cross-Origin +// Resource Sharing) rules. +// - options - BlobServicesClientSetServicePropertiesOptions contains the optional parameters for the BlobServicesClient.SetServiceProperties +// method. +func (client *BlobServicesClient) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters BlobServiceProperties, options *BlobServicesClientSetServicePropertiesOptions) (BlobServicesClientSetServicePropertiesResponse, error) { + var err error + const operationName = "BlobServicesClient.SetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return BlobServicesClientSetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobServicesClientSetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlobServicesClientSetServicePropertiesResponse{}, err + } + resp, err := client.setServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// setServicePropertiesCreateRequest creates the SetServiceProperties request. +func (client *BlobServicesClient) setServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters BlobServiceProperties, options *BlobServicesClientSetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/{BlobServicesName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{BlobServicesName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// setServicePropertiesHandleResponse handles the SetServiceProperties response. +func (client *BlobServicesClient) setServicePropertiesHandleResponse(resp *http.Response) (BlobServicesClientSetServicePropertiesResponse, error) { + result := BlobServicesClientSetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobServiceProperties); err != nil { + return BlobServicesClientSetServicePropertiesResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/build.go new file mode 100644 index 0000000000..9c22bcd53e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/storage/armstorage + +package armstorage diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/ci.yml new file mode 100644 index 0000000000..56efca76cf --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/ci.yml @@ -0,0 +1,28 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/storage/armstorage/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/storage/armstorage/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/storage/armstorage' diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/client_factory.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/client_factory.go new file mode 100644 index 0000000000..d0da80d15c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/client_factory.go @@ -0,0 +1,158 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + credential azcore.TokenCredential + options *arm.ClientOptions +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + _, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, credential: credential, + options: options.Clone(), + }, nil +} + +// NewAccountsClient creates a new instance of AccountsClient. +func (c *ClientFactory) NewAccountsClient() *AccountsClient { + subClient, _ := NewAccountsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewBlobContainersClient creates a new instance of BlobContainersClient. +func (c *ClientFactory) NewBlobContainersClient() *BlobContainersClient { + subClient, _ := NewBlobContainersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewBlobInventoryPoliciesClient creates a new instance of BlobInventoryPoliciesClient. +func (c *ClientFactory) NewBlobInventoryPoliciesClient() *BlobInventoryPoliciesClient { + subClient, _ := NewBlobInventoryPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewBlobServicesClient creates a new instance of BlobServicesClient. +func (c *ClientFactory) NewBlobServicesClient() *BlobServicesClient { + subClient, _ := NewBlobServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewDeletedAccountsClient creates a new instance of DeletedAccountsClient. +func (c *ClientFactory) NewDeletedAccountsClient() *DeletedAccountsClient { + subClient, _ := NewDeletedAccountsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewEncryptionScopesClient creates a new instance of EncryptionScopesClient. +func (c *ClientFactory) NewEncryptionScopesClient() *EncryptionScopesClient { + subClient, _ := NewEncryptionScopesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFileServicesClient creates a new instance of FileServicesClient. +func (c *ClientFactory) NewFileServicesClient() *FileServicesClient { + subClient, _ := NewFileServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewFileSharesClient creates a new instance of FileSharesClient. +func (c *ClientFactory) NewFileSharesClient() *FileSharesClient { + subClient, _ := NewFileSharesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewLocalUsersClient creates a new instance of LocalUsersClient. +func (c *ClientFactory) NewLocalUsersClient() *LocalUsersClient { + subClient, _ := NewLocalUsersClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewManagementPoliciesClient creates a new instance of ManagementPoliciesClient. +func (c *ClientFactory) NewManagementPoliciesClient() *ManagementPoliciesClient { + subClient, _ := NewManagementPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewObjectReplicationPoliciesClient creates a new instance of ObjectReplicationPoliciesClient. +func (c *ClientFactory) NewObjectReplicationPoliciesClient() *ObjectReplicationPoliciesClient { + subClient, _ := NewObjectReplicationPoliciesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + subClient, _ := NewOperationsClient(c.credential, c.options) + return subClient +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient. +func (c *ClientFactory) NewPrivateEndpointConnectionsClient() *PrivateEndpointConnectionsClient { + subClient, _ := NewPrivateEndpointConnectionsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient. +func (c *ClientFactory) NewPrivateLinkResourcesClient() *PrivateLinkResourcesClient { + subClient, _ := NewPrivateLinkResourcesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewQueueClient creates a new instance of QueueClient. +func (c *ClientFactory) NewQueueClient() *QueueClient { + subClient, _ := NewQueueClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewQueueServicesClient creates a new instance of QueueServicesClient. +func (c *ClientFactory) NewQueueServicesClient() *QueueServicesClient { + subClient, _ := NewQueueServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewSKUsClient creates a new instance of SKUsClient. +func (c *ClientFactory) NewSKUsClient() *SKUsClient { + subClient, _ := NewSKUsClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewTableClient creates a new instance of TableClient. +func (c *ClientFactory) NewTableClient() *TableClient { + subClient, _ := NewTableClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewTableServicesClient creates a new instance of TableServicesClient. +func (c *ClientFactory) NewTableServicesClient() *TableServicesClient { + subClient, _ := NewTableServicesClient(c.subscriptionID, c.credential, c.options) + return subClient +} + +// NewUsagesClient creates a new instance of UsagesClient. +func (c *ClientFactory) NewUsagesClient() *UsagesClient { + subClient, _ := NewUsagesClient(c.subscriptionID, c.credential, c.options) + return subClient +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/constants.go new file mode 100644 index 0000000000..bfd1b531c8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/constants.go @@ -0,0 +1,1274 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + moduleVersion = "v1.5.0" +) + +// AccessTier - Required for storage accounts where kind = BlobStorage. The access tier is used for billing. The 'Premium' +// access tier is the default value for premium block blobs storage account type and it cannot +// be changed for the premium block blobs storage account type. +type AccessTier string + +const ( + AccessTierCool AccessTier = "Cool" + AccessTierHot AccessTier = "Hot" + AccessTierPremium AccessTier = "Premium" +) + +// PossibleAccessTierValues returns the possible values for the AccessTier const type. +func PossibleAccessTierValues() []AccessTier { + return []AccessTier{ + AccessTierCool, + AccessTierHot, + AccessTierPremium, + } +} + +// AccountImmutabilityPolicyState - The ImmutabilityPolicy state defines the mode of the policy. Disabled state disables the +// policy, Unlocked state allows increase and decrease of immutability retention time and also allows toggling +// allowProtectedAppendWrites property, Locked state only allows the increase of the immutability retention time. A policy +// can only be created in a Disabled or Unlocked state and can be toggled between +// the two states. Only a policy in an Unlocked state can transition to a Locked state which cannot be reverted. +type AccountImmutabilityPolicyState string + +const ( + AccountImmutabilityPolicyStateDisabled AccountImmutabilityPolicyState = "Disabled" + AccountImmutabilityPolicyStateLocked AccountImmutabilityPolicyState = "Locked" + AccountImmutabilityPolicyStateUnlocked AccountImmutabilityPolicyState = "Unlocked" +) + +// PossibleAccountImmutabilityPolicyStateValues returns the possible values for the AccountImmutabilityPolicyState const type. +func PossibleAccountImmutabilityPolicyStateValues() []AccountImmutabilityPolicyState { + return []AccountImmutabilityPolicyState{ + AccountImmutabilityPolicyStateDisabled, + AccountImmutabilityPolicyStateLocked, + AccountImmutabilityPolicyStateUnlocked, + } +} + +// AccountStatus - Gets the status indicating whether the primary location of the storage account is available or unavailable. +type AccountStatus string + +const ( + AccountStatusAvailable AccountStatus = "available" + AccountStatusUnavailable AccountStatus = "unavailable" +) + +// PossibleAccountStatusValues returns the possible values for the AccountStatus const type. +func PossibleAccountStatusValues() []AccountStatus { + return []AccountStatus{ + AccountStatusAvailable, + AccountStatusUnavailable, + } +} + +// ActiveDirectoryPropertiesAccountType - Specifies the Active Directory account type for Azure Storage. +type ActiveDirectoryPropertiesAccountType string + +const ( + ActiveDirectoryPropertiesAccountTypeComputer ActiveDirectoryPropertiesAccountType = "Computer" + ActiveDirectoryPropertiesAccountTypeUser ActiveDirectoryPropertiesAccountType = "User" +) + +// PossibleActiveDirectoryPropertiesAccountTypeValues returns the possible values for the ActiveDirectoryPropertiesAccountType const type. +func PossibleActiveDirectoryPropertiesAccountTypeValues() []ActiveDirectoryPropertiesAccountType { + return []ActiveDirectoryPropertiesAccountType{ + ActiveDirectoryPropertiesAccountTypeComputer, + ActiveDirectoryPropertiesAccountTypeUser, + } +} + +// AllowedCopyScope - Restrict copy to and from Storage Accounts within an AAD tenant or with Private Links to the same VNet. +type AllowedCopyScope string + +const ( + AllowedCopyScopeAAD AllowedCopyScope = "AAD" + AllowedCopyScopePrivateLink AllowedCopyScope = "PrivateLink" +) + +// PossibleAllowedCopyScopeValues returns the possible values for the AllowedCopyScope const type. +func PossibleAllowedCopyScopeValues() []AllowedCopyScope { + return []AllowedCopyScope{ + AllowedCopyScopeAAD, + AllowedCopyScopePrivateLink, + } +} + +type BlobInventoryPolicyName string + +const ( + BlobInventoryPolicyNameDefault BlobInventoryPolicyName = "default" +) + +// PossibleBlobInventoryPolicyNameValues returns the possible values for the BlobInventoryPolicyName const type. +func PossibleBlobInventoryPolicyNameValues() []BlobInventoryPolicyName { + return []BlobInventoryPolicyName{ + BlobInventoryPolicyNameDefault, + } +} + +// BlobRestoreProgressStatus - The status of blob restore progress. Possible values are: - InProgress: Indicates that blob +// restore is ongoing. - Complete: Indicates that blob restore has been completed successfully. - Failed: +// Indicates that blob restore is failed. +type BlobRestoreProgressStatus string + +const ( + BlobRestoreProgressStatusComplete BlobRestoreProgressStatus = "Complete" + BlobRestoreProgressStatusFailed BlobRestoreProgressStatus = "Failed" + BlobRestoreProgressStatusInProgress BlobRestoreProgressStatus = "InProgress" +) + +// PossibleBlobRestoreProgressStatusValues returns the possible values for the BlobRestoreProgressStatus const type. +func PossibleBlobRestoreProgressStatusValues() []BlobRestoreProgressStatus { + return []BlobRestoreProgressStatus{ + BlobRestoreProgressStatusComplete, + BlobRestoreProgressStatusFailed, + BlobRestoreProgressStatusInProgress, + } +} + +// Bypass - Specifies whether traffic is bypassed for Logging/Metrics/AzureServices. Possible values are any combination of +// Logging|Metrics|AzureServices (For example, "Logging, Metrics"), or None to bypass none +// of those traffics. +type Bypass string + +const ( + BypassAzureServices Bypass = "AzureServices" + BypassLogging Bypass = "Logging" + BypassMetrics Bypass = "Metrics" + BypassNone Bypass = "None" +) + +// PossibleBypassValues returns the possible values for the Bypass const type. +func PossibleBypassValues() []Bypass { + return []Bypass{ + BypassAzureServices, + BypassLogging, + BypassMetrics, + BypassNone, + } +} + +type CorsRuleAllowedMethodsItem string + +const ( + CorsRuleAllowedMethodsItemCONNECT CorsRuleAllowedMethodsItem = "CONNECT" + CorsRuleAllowedMethodsItemDELETE CorsRuleAllowedMethodsItem = "DELETE" + CorsRuleAllowedMethodsItemGET CorsRuleAllowedMethodsItem = "GET" + CorsRuleAllowedMethodsItemHEAD CorsRuleAllowedMethodsItem = "HEAD" + CorsRuleAllowedMethodsItemMERGE CorsRuleAllowedMethodsItem = "MERGE" + CorsRuleAllowedMethodsItemOPTIONS CorsRuleAllowedMethodsItem = "OPTIONS" + CorsRuleAllowedMethodsItemPATCH CorsRuleAllowedMethodsItem = "PATCH" + CorsRuleAllowedMethodsItemPOST CorsRuleAllowedMethodsItem = "POST" + CorsRuleAllowedMethodsItemPUT CorsRuleAllowedMethodsItem = "PUT" + CorsRuleAllowedMethodsItemTRACE CorsRuleAllowedMethodsItem = "TRACE" +) + +// PossibleCorsRuleAllowedMethodsItemValues returns the possible values for the CorsRuleAllowedMethodsItem const type. +func PossibleCorsRuleAllowedMethodsItemValues() []CorsRuleAllowedMethodsItem { + return []CorsRuleAllowedMethodsItem{ + CorsRuleAllowedMethodsItemCONNECT, + CorsRuleAllowedMethodsItemDELETE, + CorsRuleAllowedMethodsItemGET, + CorsRuleAllowedMethodsItemHEAD, + CorsRuleAllowedMethodsItemMERGE, + CorsRuleAllowedMethodsItemOPTIONS, + CorsRuleAllowedMethodsItemPATCH, + CorsRuleAllowedMethodsItemPOST, + CorsRuleAllowedMethodsItemPUT, + CorsRuleAllowedMethodsItemTRACE, + } +} + +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DNSEndpointType - Allows you to specify the type of endpoint. Set this to AzureDNSZone to create a large number of accounts +// in a single subscription, which creates accounts in an Azure DNS Zone and the endpoint URL +// will have an alphanumeric DNS Zone identifier. +type DNSEndpointType string + +const ( + DNSEndpointTypeAzureDNSZone DNSEndpointType = "AzureDnsZone" + DNSEndpointTypeStandard DNSEndpointType = "Standard" +) + +// PossibleDNSEndpointTypeValues returns the possible values for the DNSEndpointType const type. +func PossibleDNSEndpointTypeValues() []DNSEndpointType { + return []DNSEndpointType{ + DNSEndpointTypeAzureDNSZone, + DNSEndpointTypeStandard, + } +} + +// DefaultAction - Specifies the default action of allow or deny when no other rules match. +type DefaultAction string + +const ( + DefaultActionAllow DefaultAction = "Allow" + DefaultActionDeny DefaultAction = "Deny" +) + +// PossibleDefaultActionValues returns the possible values for the DefaultAction const type. +func PossibleDefaultActionValues() []DefaultAction { + return []DefaultAction{ + DefaultActionAllow, + DefaultActionDeny, + } +} + +// DefaultSharePermission - Default share permission for users using Kerberos authentication if RBAC role is not assigned. +type DefaultSharePermission string + +const ( + DefaultSharePermissionNone DefaultSharePermission = "None" + DefaultSharePermissionStorageFileDataSmbShareContributor DefaultSharePermission = "StorageFileDataSmbShareContributor" + DefaultSharePermissionStorageFileDataSmbShareElevatedContributor DefaultSharePermission = "StorageFileDataSmbShareElevatedContributor" + DefaultSharePermissionStorageFileDataSmbShareReader DefaultSharePermission = "StorageFileDataSmbShareReader" +) + +// PossibleDefaultSharePermissionValues returns the possible values for the DefaultSharePermission const type. +func PossibleDefaultSharePermissionValues() []DefaultSharePermission { + return []DefaultSharePermission{ + DefaultSharePermissionNone, + DefaultSharePermissionStorageFileDataSmbShareContributor, + DefaultSharePermissionStorageFileDataSmbShareElevatedContributor, + DefaultSharePermissionStorageFileDataSmbShareReader, + } +} + +// DirectoryServiceOptions - Indicates the directory service used. Note that this enum may be extended in the future. +type DirectoryServiceOptions string + +const ( + DirectoryServiceOptionsAADDS DirectoryServiceOptions = "AADDS" + DirectoryServiceOptionsAADKERB DirectoryServiceOptions = "AADKERB" + DirectoryServiceOptionsAD DirectoryServiceOptions = "AD" + DirectoryServiceOptionsNone DirectoryServiceOptions = "None" +) + +// PossibleDirectoryServiceOptionsValues returns the possible values for the DirectoryServiceOptions const type. +func PossibleDirectoryServiceOptionsValues() []DirectoryServiceOptions { + return []DirectoryServiceOptions{ + DirectoryServiceOptionsAADDS, + DirectoryServiceOptionsAADKERB, + DirectoryServiceOptionsAD, + DirectoryServiceOptionsNone, + } +} + +// EnabledProtocols - The authentication protocol that is used for the file share. Can only be specified when creating a share. +type EnabledProtocols string + +const ( + EnabledProtocolsNFS EnabledProtocols = "NFS" + EnabledProtocolsSMB EnabledProtocols = "SMB" +) + +// PossibleEnabledProtocolsValues returns the possible values for the EnabledProtocols const type. +func PossibleEnabledProtocolsValues() []EnabledProtocols { + return []EnabledProtocols{ + EnabledProtocolsNFS, + EnabledProtocolsSMB, + } +} + +// EncryptionScopeSource - The provider for the encryption scope. Possible values (case-insensitive): Microsoft.Storage, Microsoft.KeyVault. +type EncryptionScopeSource string + +const ( + EncryptionScopeSourceMicrosoftKeyVault EncryptionScopeSource = "Microsoft.KeyVault" + EncryptionScopeSourceMicrosoftStorage EncryptionScopeSource = "Microsoft.Storage" +) + +// PossibleEncryptionScopeSourceValues returns the possible values for the EncryptionScopeSource const type. +func PossibleEncryptionScopeSourceValues() []EncryptionScopeSource { + return []EncryptionScopeSource{ + EncryptionScopeSourceMicrosoftKeyVault, + EncryptionScopeSourceMicrosoftStorage, + } +} + +// EncryptionScopeState - The state of the encryption scope. Possible values (case-insensitive): Enabled, Disabled. +type EncryptionScopeState string + +const ( + EncryptionScopeStateDisabled EncryptionScopeState = "Disabled" + EncryptionScopeStateEnabled EncryptionScopeState = "Enabled" +) + +// PossibleEncryptionScopeStateValues returns the possible values for the EncryptionScopeState const type. +func PossibleEncryptionScopeStateValues() []EncryptionScopeState { + return []EncryptionScopeState{ + EncryptionScopeStateDisabled, + EncryptionScopeStateEnabled, + } +} + +// ExpirationAction - The SAS expiration action. Can only be Log. +type ExpirationAction string + +const ( + ExpirationActionLog ExpirationAction = "Log" +) + +// PossibleExpirationActionValues returns the possible values for the ExpirationAction const type. +func PossibleExpirationActionValues() []ExpirationAction { + return []ExpirationAction{ + ExpirationActionLog, + } +} + +// ExtendedLocationTypes - The type of extendedLocation. +type ExtendedLocationTypes string + +const ( + ExtendedLocationTypesEdgeZone ExtendedLocationTypes = "EdgeZone" +) + +// PossibleExtendedLocationTypesValues returns the possible values for the ExtendedLocationTypes const type. +func PossibleExtendedLocationTypesValues() []ExtendedLocationTypes { + return []ExtendedLocationTypes{ + ExtendedLocationTypesEdgeZone, + } +} + +// Format - This is a required field, it specifies the format for the inventory files. +type Format string + +const ( + FormatCSV Format = "Csv" + FormatParquet Format = "Parquet" +) + +// PossibleFormatValues returns the possible values for the Format const type. +func PossibleFormatValues() []Format { + return []Format{ + FormatCSV, + FormatParquet, + } +} + +// GeoReplicationStatus - The status of the secondary location. Possible values are: - Live: Indicates that the secondary +// location is active and operational. - Bootstrap: Indicates initial synchronization from the primary +// location to the secondary location is in progress.This typically occurs when replication is first enabled. - Unavailable: +// Indicates that the secondary location is temporarily unavailable. +type GeoReplicationStatus string + +const ( + GeoReplicationStatusBootstrap GeoReplicationStatus = "Bootstrap" + GeoReplicationStatusLive GeoReplicationStatus = "Live" + GeoReplicationStatusUnavailable GeoReplicationStatus = "Unavailable" +) + +// PossibleGeoReplicationStatusValues returns the possible values for the GeoReplicationStatus const type. +func PossibleGeoReplicationStatusValues() []GeoReplicationStatus { + return []GeoReplicationStatus{ + GeoReplicationStatusBootstrap, + GeoReplicationStatusLive, + GeoReplicationStatusUnavailable, + } +} + +// HTTPProtocol - The protocol permitted for a request made with the account SAS. +type HTTPProtocol string + +const ( + HTTPProtocolHTTPS HTTPProtocol = "https" + HTTPProtocolHTTPSHTTP HTTPProtocol = "https,http" +) + +// PossibleHTTPProtocolValues returns the possible values for the HTTPProtocol const type. +func PossibleHTTPProtocolValues() []HTTPProtocol { + return []HTTPProtocol{ + HTTPProtocolHTTPS, + HTTPProtocolHTTPSHTTP, + } +} + +// IdentityType - The identity type. +type IdentityType string + +const ( + IdentityTypeNone IdentityType = "None" + IdentityTypeSystemAssigned IdentityType = "SystemAssigned" + IdentityTypeSystemAssignedUserAssigned IdentityType = "SystemAssigned,UserAssigned" + IdentityTypeUserAssigned IdentityType = "UserAssigned" +) + +// PossibleIdentityTypeValues returns the possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{ + IdentityTypeNone, + IdentityTypeSystemAssigned, + IdentityTypeSystemAssignedUserAssigned, + IdentityTypeUserAssigned, + } +} + +// ImmutabilityPolicyState - The ImmutabilityPolicy state of a blob container, possible values include: Locked and Unlocked. +type ImmutabilityPolicyState string + +const ( + ImmutabilityPolicyStateLocked ImmutabilityPolicyState = "Locked" + ImmutabilityPolicyStateUnlocked ImmutabilityPolicyState = "Unlocked" +) + +// PossibleImmutabilityPolicyStateValues returns the possible values for the ImmutabilityPolicyState const type. +func PossibleImmutabilityPolicyStateValues() []ImmutabilityPolicyState { + return []ImmutabilityPolicyState{ + ImmutabilityPolicyStateLocked, + ImmutabilityPolicyStateUnlocked, + } +} + +// ImmutabilityPolicyUpdateType - The ImmutabilityPolicy update type of a blob container, possible values include: put, lock +// and extend. +type ImmutabilityPolicyUpdateType string + +const ( + ImmutabilityPolicyUpdateTypeExtend ImmutabilityPolicyUpdateType = "extend" + ImmutabilityPolicyUpdateTypeLock ImmutabilityPolicyUpdateType = "lock" + ImmutabilityPolicyUpdateTypePut ImmutabilityPolicyUpdateType = "put" +) + +// PossibleImmutabilityPolicyUpdateTypeValues returns the possible values for the ImmutabilityPolicyUpdateType const type. +func PossibleImmutabilityPolicyUpdateTypeValues() []ImmutabilityPolicyUpdateType { + return []ImmutabilityPolicyUpdateType{ + ImmutabilityPolicyUpdateTypeExtend, + ImmutabilityPolicyUpdateTypeLock, + ImmutabilityPolicyUpdateTypePut, + } +} + +// InventoryRuleType - The valid value is Inventory +type InventoryRuleType string + +const ( + InventoryRuleTypeInventory InventoryRuleType = "Inventory" +) + +// PossibleInventoryRuleTypeValues returns the possible values for the InventoryRuleType const type. +func PossibleInventoryRuleTypeValues() []InventoryRuleType { + return []InventoryRuleType{ + InventoryRuleTypeInventory, + } +} + +// KeyPermission - Permissions for the key -- read-only or full permissions. +type KeyPermission string + +const ( + KeyPermissionFull KeyPermission = "Full" + KeyPermissionRead KeyPermission = "Read" +) + +// PossibleKeyPermissionValues returns the possible values for the KeyPermission const type. +func PossibleKeyPermissionValues() []KeyPermission { + return []KeyPermission{ + KeyPermissionFull, + KeyPermissionRead, + } +} + +// KeySource - The encryption keySource (provider). Possible values (case-insensitive): Microsoft.Storage, Microsoft.Keyvault +type KeySource string + +const ( + KeySourceMicrosoftKeyvault KeySource = "Microsoft.Keyvault" + KeySourceMicrosoftStorage KeySource = "Microsoft.Storage" +) + +// PossibleKeySourceValues returns the possible values for the KeySource const type. +func PossibleKeySourceValues() []KeySource { + return []KeySource{ + KeySourceMicrosoftKeyvault, + KeySourceMicrosoftStorage, + } +} + +// KeyType - Encryption key type to be used for the encryption service. 'Account' key type implies that an account-scoped +// encryption key will be used. 'Service' key type implies that a default service key is used. +type KeyType string + +const ( + KeyTypeAccount KeyType = "Account" + KeyTypeService KeyType = "Service" +) + +// PossibleKeyTypeValues returns the possible values for the KeyType const type. +func PossibleKeyTypeValues() []KeyType { + return []KeyType{ + KeyTypeAccount, + KeyTypeService, + } +} + +// Kind - Indicates the type of storage account. +type Kind string + +const ( + KindBlobStorage Kind = "BlobStorage" + KindBlockBlobStorage Kind = "BlockBlobStorage" + KindFileStorage Kind = "FileStorage" + KindStorage Kind = "Storage" + KindStorageV2 Kind = "StorageV2" +) + +// PossibleKindValues returns the possible values for the Kind const type. +func PossibleKindValues() []Kind { + return []Kind{ + KindBlobStorage, + KindBlockBlobStorage, + KindFileStorage, + KindStorage, + KindStorageV2, + } +} + +// LargeFileSharesState - Allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. +type LargeFileSharesState string + +const ( + LargeFileSharesStateDisabled LargeFileSharesState = "Disabled" + LargeFileSharesStateEnabled LargeFileSharesState = "Enabled" +) + +// PossibleLargeFileSharesStateValues returns the possible values for the LargeFileSharesState const type. +func PossibleLargeFileSharesStateValues() []LargeFileSharesState { + return []LargeFileSharesState{ + LargeFileSharesStateDisabled, + LargeFileSharesStateEnabled, + } +} + +// LeaseContainerRequestAction - Specifies the lease action. Can be one of the available actions. +type LeaseContainerRequestAction string + +const ( + LeaseContainerRequestActionAcquire LeaseContainerRequestAction = "Acquire" + LeaseContainerRequestActionBreak LeaseContainerRequestAction = "Break" + LeaseContainerRequestActionChange LeaseContainerRequestAction = "Change" + LeaseContainerRequestActionRelease LeaseContainerRequestAction = "Release" + LeaseContainerRequestActionRenew LeaseContainerRequestAction = "Renew" +) + +// PossibleLeaseContainerRequestActionValues returns the possible values for the LeaseContainerRequestAction const type. +func PossibleLeaseContainerRequestActionValues() []LeaseContainerRequestAction { + return []LeaseContainerRequestAction{ + LeaseContainerRequestActionAcquire, + LeaseContainerRequestActionBreak, + LeaseContainerRequestActionChange, + LeaseContainerRequestActionRelease, + LeaseContainerRequestActionRenew, + } +} + +// LeaseDuration - Specifies whether the lease on a container is of infinite or fixed duration, only when the container is +// leased. +type LeaseDuration string + +const ( + LeaseDurationFixed LeaseDuration = "Fixed" + LeaseDurationInfinite LeaseDuration = "Infinite" +) + +// PossibleLeaseDurationValues returns the possible values for the LeaseDuration const type. +func PossibleLeaseDurationValues() []LeaseDuration { + return []LeaseDuration{ + LeaseDurationFixed, + LeaseDurationInfinite, + } +} + +// LeaseShareAction - Specifies the lease action. Can be one of the available actions. +type LeaseShareAction string + +const ( + LeaseShareActionAcquire LeaseShareAction = "Acquire" + LeaseShareActionBreak LeaseShareAction = "Break" + LeaseShareActionChange LeaseShareAction = "Change" + LeaseShareActionRelease LeaseShareAction = "Release" + LeaseShareActionRenew LeaseShareAction = "Renew" +) + +// PossibleLeaseShareActionValues returns the possible values for the LeaseShareAction const type. +func PossibleLeaseShareActionValues() []LeaseShareAction { + return []LeaseShareAction{ + LeaseShareActionAcquire, + LeaseShareActionBreak, + LeaseShareActionChange, + LeaseShareActionRelease, + LeaseShareActionRenew, + } +} + +// LeaseState - Lease state of the container. +type LeaseState string + +const ( + LeaseStateAvailable LeaseState = "Available" + LeaseStateBreaking LeaseState = "Breaking" + LeaseStateBroken LeaseState = "Broken" + LeaseStateExpired LeaseState = "Expired" + LeaseStateLeased LeaseState = "Leased" +) + +// PossibleLeaseStateValues returns the possible values for the LeaseState const type. +func PossibleLeaseStateValues() []LeaseState { + return []LeaseState{ + LeaseStateAvailable, + LeaseStateBreaking, + LeaseStateBroken, + LeaseStateExpired, + LeaseStateLeased, + } +} + +// LeaseStatus - The lease status of the container. +type LeaseStatus string + +const ( + LeaseStatusLocked LeaseStatus = "Locked" + LeaseStatusUnlocked LeaseStatus = "Unlocked" +) + +// PossibleLeaseStatusValues returns the possible values for the LeaseStatus const type. +func PossibleLeaseStatusValues() []LeaseStatus { + return []LeaseStatus{ + LeaseStatusLocked, + LeaseStatusUnlocked, + } +} + +type ListContainersInclude string + +const ( + ListContainersIncludeDeleted ListContainersInclude = "deleted" +) + +// PossibleListContainersIncludeValues returns the possible values for the ListContainersInclude const type. +func PossibleListContainersIncludeValues() []ListContainersInclude { + return []ListContainersInclude{ + ListContainersIncludeDeleted, + } +} + +type ListEncryptionScopesInclude string + +const ( + ListEncryptionScopesIncludeAll ListEncryptionScopesInclude = "All" + ListEncryptionScopesIncludeDisabled ListEncryptionScopesInclude = "Disabled" + ListEncryptionScopesIncludeEnabled ListEncryptionScopesInclude = "Enabled" +) + +// PossibleListEncryptionScopesIncludeValues returns the possible values for the ListEncryptionScopesInclude const type. +func PossibleListEncryptionScopesIncludeValues() []ListEncryptionScopesInclude { + return []ListEncryptionScopesInclude{ + ListEncryptionScopesIncludeAll, + ListEncryptionScopesIncludeDisabled, + ListEncryptionScopesIncludeEnabled, + } +} + +type ManagementPolicyName string + +const ( + ManagementPolicyNameDefault ManagementPolicyName = "default" +) + +// PossibleManagementPolicyNameValues returns the possible values for the ManagementPolicyName const type. +func PossibleManagementPolicyNameValues() []ManagementPolicyName { + return []ManagementPolicyName{ + ManagementPolicyNameDefault, + } +} + +type MigrationName string + +const ( + MigrationNameDefault MigrationName = "default" +) + +// PossibleMigrationNameValues returns the possible values for the MigrationName const type. +func PossibleMigrationNameValues() []MigrationName { + return []MigrationName{ + MigrationNameDefault, + } +} + +// MigrationState - This property denotes the container level immutability to object level immutability migration state. +type MigrationState string + +const ( + MigrationStateCompleted MigrationState = "Completed" + MigrationStateInProgress MigrationState = "InProgress" +) + +// PossibleMigrationStateValues returns the possible values for the MigrationState const type. +func PossibleMigrationStateValues() []MigrationState { + return []MigrationState{ + MigrationStateCompleted, + MigrationStateInProgress, + } +} + +// MigrationStatus - Current status of migration +type MigrationStatus string + +const ( + MigrationStatusComplete MigrationStatus = "Complete" + MigrationStatusFailed MigrationStatus = "Failed" + MigrationStatusInProgress MigrationStatus = "InProgress" + MigrationStatusInvalid MigrationStatus = "Invalid" + MigrationStatusSubmittedForConversion MigrationStatus = "SubmittedForConversion" +) + +// PossibleMigrationStatusValues returns the possible values for the MigrationStatus const type. +func PossibleMigrationStatusValues() []MigrationStatus { + return []MigrationStatus{ + MigrationStatusComplete, + MigrationStatusFailed, + MigrationStatusInProgress, + MigrationStatusInvalid, + MigrationStatusSubmittedForConversion, + } +} + +// MinimumTLSVersion - Set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS +// 1.0 for this property. +type MinimumTLSVersion string + +const ( + MinimumTLSVersionTLS10 MinimumTLSVersion = "TLS1_0" + MinimumTLSVersionTLS11 MinimumTLSVersion = "TLS1_1" + MinimumTLSVersionTLS12 MinimumTLSVersion = "TLS1_2" +) + +// PossibleMinimumTLSVersionValues returns the possible values for the MinimumTLSVersion const type. +func PossibleMinimumTLSVersionValues() []MinimumTLSVersion { + return []MinimumTLSVersion{ + MinimumTLSVersionTLS10, + MinimumTLSVersionTLS11, + MinimumTLSVersionTLS12, + } +} + +// Name - Name of the policy. The valid value is AccessTimeTracking. This field is currently read only +type Name string + +const ( + NameAccessTimeTracking Name = "AccessTimeTracking" +) + +// PossibleNameValues returns the possible values for the Name const type. +func PossibleNameValues() []Name { + return []Name{ + NameAccessTimeTracking, + } +} + +// ObjectType - This is a required field. This field specifies the scope of the inventory created either at the blob or container +// level. +type ObjectType string + +const ( + ObjectTypeBlob ObjectType = "Blob" + ObjectTypeContainer ObjectType = "Container" +) + +// PossibleObjectTypeValues returns the possible values for the ObjectType const type. +func PossibleObjectTypeValues() []ObjectType { + return []ObjectType{ + ObjectTypeBlob, + ObjectTypeContainer, + } +} + +// Permissions - The signed permissions for the account SAS. Possible values include: Read (r), Write (w), Delete (d), List +// (l), Add (a), Create (c), Update (u) and Process (p). +type Permissions string + +const ( + PermissionsA Permissions = "a" + PermissionsC Permissions = "c" + PermissionsD Permissions = "d" + PermissionsL Permissions = "l" + PermissionsP Permissions = "p" + PermissionsR Permissions = "r" + PermissionsU Permissions = "u" + PermissionsW Permissions = "w" +) + +// PossiblePermissionsValues returns the possible values for the Permissions const type. +func PossiblePermissionsValues() []Permissions { + return []Permissions{ + PermissionsA, + PermissionsC, + PermissionsD, + PermissionsL, + PermissionsP, + PermissionsR, + PermissionsU, + PermissionsW, + } +} + +// PostFailoverRedundancy - The redundancy type of the account after an account failover is performed. +type PostFailoverRedundancy string + +const ( + PostFailoverRedundancyStandardLRS PostFailoverRedundancy = "Standard_LRS" + PostFailoverRedundancyStandardZRS PostFailoverRedundancy = "Standard_ZRS" +) + +// PossiblePostFailoverRedundancyValues returns the possible values for the PostFailoverRedundancy const type. +func PossiblePostFailoverRedundancyValues() []PostFailoverRedundancy { + return []PostFailoverRedundancy{ + PostFailoverRedundancyStandardLRS, + PostFailoverRedundancyStandardZRS, + } +} + +// PostPlannedFailoverRedundancy - The redundancy type of the account after a planned account failover is performed. +type PostPlannedFailoverRedundancy string + +const ( + PostPlannedFailoverRedundancyStandardGRS PostPlannedFailoverRedundancy = "Standard_GRS" + PostPlannedFailoverRedundancyStandardGZRS PostPlannedFailoverRedundancy = "Standard_GZRS" + PostPlannedFailoverRedundancyStandardRAGRS PostPlannedFailoverRedundancy = "Standard_RAGRS" + PostPlannedFailoverRedundancyStandardRAGZRS PostPlannedFailoverRedundancy = "Standard_RAGZRS" +) + +// PossiblePostPlannedFailoverRedundancyValues returns the possible values for the PostPlannedFailoverRedundancy const type. +func PossiblePostPlannedFailoverRedundancyValues() []PostPlannedFailoverRedundancy { + return []PostPlannedFailoverRedundancy{ + PostPlannedFailoverRedundancyStandardGRS, + PostPlannedFailoverRedundancyStandardGZRS, + PostPlannedFailoverRedundancyStandardRAGRS, + PostPlannedFailoverRedundancyStandardRAGZRS, + } +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + } +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// ProvisioningState - Gets the status of the storage account at the time the operation was called. +type ProvisioningState string + +const ( + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateResolvingDNS ProvisioningState = "ResolvingDNS" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCreating, + ProvisioningStateResolvingDNS, + ProvisioningStateSucceeded, + } +} + +// PublicAccess - Specifies whether data in the container may be accessed publicly and the level of access. +type PublicAccess string + +const ( + PublicAccessBlob PublicAccess = "Blob" + PublicAccessContainer PublicAccess = "Container" + PublicAccessNone PublicAccess = "None" +) + +// PossiblePublicAccessValues returns the possible values for the PublicAccess const type. +func PossiblePublicAccessValues() []PublicAccess { + return []PublicAccess{ + PublicAccessBlob, + PublicAccessContainer, + PublicAccessNone, + } +} + +// PublicNetworkAccess - Allow or disallow public network access to Storage Account. Value is optional but if passed in, must +// be 'Enabled' or 'Disabled'. +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// Reason - Gets the reason that a storage account name could not be used. The Reason element is only returned if NameAvailable +// is false. +type Reason string + +const ( + ReasonAccountNameInvalid Reason = "AccountNameInvalid" + ReasonAlreadyExists Reason = "AlreadyExists" +) + +// PossibleReasonValues returns the possible values for the Reason const type. +func PossibleReasonValues() []Reason { + return []Reason{ + ReasonAccountNameInvalid, + ReasonAlreadyExists, + } +} + +// ReasonCode - The reason for the restriction. As of now this can be "QuotaId" or "NotAvailableForSubscription". Quota Id +// is set when the SKU has requiredQuotas parameter as the subscription does not belong to that +// quota. The "NotAvailableForSubscription" is related to capacity at DC. +type ReasonCode string + +const ( + ReasonCodeNotAvailableForSubscription ReasonCode = "NotAvailableForSubscription" + ReasonCodeQuotaID ReasonCode = "QuotaId" +) + +// PossibleReasonCodeValues returns the possible values for the ReasonCode const type. +func PossibleReasonCodeValues() []ReasonCode { + return []ReasonCode{ + ReasonCodeNotAvailableForSubscription, + ReasonCodeQuotaID, + } +} + +// RootSquashType - The property is for NFS share only. The default is NoRootSquash. +type RootSquashType string + +const ( + RootSquashTypeAllSquash RootSquashType = "AllSquash" + RootSquashTypeNoRootSquash RootSquashType = "NoRootSquash" + RootSquashTypeRootSquash RootSquashType = "RootSquash" +) + +// PossibleRootSquashTypeValues returns the possible values for the RootSquashType const type. +func PossibleRootSquashTypeValues() []RootSquashType { + return []RootSquashType{ + RootSquashTypeAllSquash, + RootSquashTypeNoRootSquash, + RootSquashTypeRootSquash, + } +} + +// RoutingChoice - Routing Choice defines the kind of network routing opted by the user. +type RoutingChoice string + +const ( + RoutingChoiceInternetRouting RoutingChoice = "InternetRouting" + RoutingChoiceMicrosoftRouting RoutingChoice = "MicrosoftRouting" +) + +// PossibleRoutingChoiceValues returns the possible values for the RoutingChoice const type. +func PossibleRoutingChoiceValues() []RoutingChoice { + return []RoutingChoice{ + RoutingChoiceInternetRouting, + RoutingChoiceMicrosoftRouting, + } +} + +// RuleType - The valid value is Lifecycle +type RuleType string + +const ( + RuleTypeLifecycle RuleType = "Lifecycle" +) + +// PossibleRuleTypeValues returns the possible values for the RuleType const type. +func PossibleRuleTypeValues() []RuleType { + return []RuleType{ + RuleTypeLifecycle, + } +} + +// SKUConversionStatus - This property indicates the current sku conversion status. +type SKUConversionStatus string + +const ( + SKUConversionStatusFailed SKUConversionStatus = "Failed" + SKUConversionStatusInProgress SKUConversionStatus = "InProgress" + SKUConversionStatusSucceeded SKUConversionStatus = "Succeeded" +) + +// PossibleSKUConversionStatusValues returns the possible values for the SKUConversionStatus const type. +func PossibleSKUConversionStatusValues() []SKUConversionStatus { + return []SKUConversionStatus{ + SKUConversionStatusFailed, + SKUConversionStatusInProgress, + SKUConversionStatusSucceeded, + } +} + +// SKUName - The SKU name. Required for account creation; optional for update. Note that in older versions, SKU name was called +// accountType. +type SKUName string + +const ( + SKUNamePremiumLRS SKUName = "Premium_LRS" + SKUNamePremiumZRS SKUName = "Premium_ZRS" + SKUNameStandardGRS SKUName = "Standard_GRS" + SKUNameStandardGZRS SKUName = "Standard_GZRS" + SKUNameStandardLRS SKUName = "Standard_LRS" + SKUNameStandardRAGRS SKUName = "Standard_RAGRS" + SKUNameStandardRAGZRS SKUName = "Standard_RAGZRS" + SKUNameStandardZRS SKUName = "Standard_ZRS" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNamePremiumLRS, + SKUNamePremiumZRS, + SKUNameStandardGRS, + SKUNameStandardGZRS, + SKUNameStandardLRS, + SKUNameStandardRAGRS, + SKUNameStandardRAGZRS, + SKUNameStandardZRS, + } +} + +// SKUTier - The SKU tier. This is based on the SKU name. +type SKUTier string + +const ( + SKUTierPremium SKUTier = "Premium" + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierPremium, + SKUTierStandard, + } +} + +// Schedule - This is a required field. This field is used to schedule an inventory formation. +type Schedule string + +const ( + ScheduleDaily Schedule = "Daily" + ScheduleWeekly Schedule = "Weekly" +) + +// PossibleScheduleValues returns the possible values for the Schedule const type. +func PossibleScheduleValues() []Schedule { + return []Schedule{ + ScheduleDaily, + ScheduleWeekly, + } +} + +// Services - The signed services accessible with the account SAS. Possible values include: Blob (b), Queue (q), Table (t), +// File (f). +type Services string + +const ( + ServicesB Services = "b" + ServicesF Services = "f" + ServicesQ Services = "q" + ServicesT Services = "t" +) + +// PossibleServicesValues returns the possible values for the Services const type. +func PossibleServicesValues() []Services { + return []Services{ + ServicesB, + ServicesF, + ServicesQ, + ServicesT, + } +} + +// ShareAccessTier - Access tier for specific share. GpV2 account can choose between TransactionOptimized (default), Hot, +// and Cool. FileStorage account can choose Premium. +type ShareAccessTier string + +const ( + ShareAccessTierCool ShareAccessTier = "Cool" + ShareAccessTierHot ShareAccessTier = "Hot" + ShareAccessTierPremium ShareAccessTier = "Premium" + ShareAccessTierTransactionOptimized ShareAccessTier = "TransactionOptimized" +) + +// PossibleShareAccessTierValues returns the possible values for the ShareAccessTier const type. +func PossibleShareAccessTierValues() []ShareAccessTier { + return []ShareAccessTier{ + ShareAccessTierCool, + ShareAccessTierHot, + ShareAccessTierPremium, + ShareAccessTierTransactionOptimized, + } +} + +// SignedResource - The signed services accessible with the service SAS. Possible values include: Blob (b), Container (c), +// File (f), Share (s). +type SignedResource string + +const ( + SignedResourceB SignedResource = "b" + SignedResourceC SignedResource = "c" + SignedResourceF SignedResource = "f" + SignedResourceS SignedResource = "s" +) + +// PossibleSignedResourceValues returns the possible values for the SignedResource const type. +func PossibleSignedResourceValues() []SignedResource { + return []SignedResource{ + SignedResourceB, + SignedResourceC, + SignedResourceF, + SignedResourceS, + } +} + +// SignedResourceTypes - The signed resource types that are accessible with the account SAS. Service (s): Access to service-level +// APIs; Container (c): Access to container-level APIs; Object (o): Access to object-level APIs +// for blobs, queue messages, table entities, and files. +type SignedResourceTypes string + +const ( + SignedResourceTypesC SignedResourceTypes = "c" + SignedResourceTypesO SignedResourceTypes = "o" + SignedResourceTypesS SignedResourceTypes = "s" +) + +// PossibleSignedResourceTypesValues returns the possible values for the SignedResourceTypes const type. +func PossibleSignedResourceTypesValues() []SignedResourceTypes { + return []SignedResourceTypes{ + SignedResourceTypesC, + SignedResourceTypesO, + SignedResourceTypesS, + } +} + +// State - Gets the state of virtual network rule. +type State string + +const ( + StateDeprovisioning State = "Deprovisioning" + StateFailed State = "Failed" + StateNetworkSourceDeleted State = "NetworkSourceDeleted" + StateProvisioning State = "Provisioning" + StateSucceeded State = "Succeeded" +) + +// PossibleStateValues returns the possible values for the State const type. +func PossibleStateValues() []State { + return []State{ + StateDeprovisioning, + StateFailed, + StateNetworkSourceDeleted, + StateProvisioning, + StateSucceeded, + } +} + +type StorageAccountExpand string + +const ( + StorageAccountExpandBlobRestoreStatus StorageAccountExpand = "blobRestoreStatus" + StorageAccountExpandGeoReplicationStats StorageAccountExpand = "geoReplicationStats" +) + +// PossibleStorageAccountExpandValues returns the possible values for the StorageAccountExpand const type. +func PossibleStorageAccountExpandValues() []StorageAccountExpand { + return []StorageAccountExpand{ + StorageAccountExpandBlobRestoreStatus, + StorageAccountExpandGeoReplicationStats, + } +} + +// UsageUnit - Gets the unit of measurement. +type UsageUnit string + +const ( + UsageUnitBytes UsageUnit = "Bytes" + UsageUnitBytesPerSecond UsageUnit = "BytesPerSecond" + UsageUnitCount UsageUnit = "Count" + UsageUnitCountsPerSecond UsageUnit = "CountsPerSecond" + UsageUnitPercent UsageUnit = "Percent" + UsageUnitSeconds UsageUnit = "Seconds" +) + +// PossibleUsageUnitValues returns the possible values for the UsageUnit const type. +func PossibleUsageUnitValues() []UsageUnit { + return []UsageUnit{ + UsageUnitBytes, + UsageUnitBytesPerSecond, + UsageUnitCount, + UsageUnitCountsPerSecond, + UsageUnitPercent, + UsageUnitSeconds, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/deletedaccounts_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/deletedaccounts_client.go new file mode 100644 index 0000000000..438fc77ee9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/deletedaccounts_client.go @@ -0,0 +1,163 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DeletedAccountsClient contains the methods for the DeletedAccounts group. +// Don't use this type directly, use NewDeletedAccountsClient() instead. +type DeletedAccountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDeletedAccountsClient creates a new instance of DeletedAccountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewDeletedAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeletedAccountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DeletedAccountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get properties of specified deleted account resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - deletedAccountName - Name of the deleted storage account. +// - location - The location of the deleted storage account. +// - options - DeletedAccountsClientGetOptions contains the optional parameters for the DeletedAccountsClient.Get method. +func (client *DeletedAccountsClient) Get(ctx context.Context, deletedAccountName string, location string, options *DeletedAccountsClientGetOptions) (DeletedAccountsClientGetResponse, error) { + var err error + const operationName = "DeletedAccountsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, deletedAccountName, location, options) + if err != nil { + return DeletedAccountsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeletedAccountsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeletedAccountsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DeletedAccountsClient) getCreateRequest(ctx context.Context, deletedAccountName string, location string, options *DeletedAccountsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/locations/{location}/deletedAccounts/{deletedAccountName}" + if deletedAccountName == "" { + return nil, errors.New("parameter deletedAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deletedAccountName}", url.PathEscape(deletedAccountName)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeletedAccountsClient) getHandleResponse(resp *http.Response) (DeletedAccountsClientGetResponse, error) { + result := DeletedAccountsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedAccount); err != nil { + return DeletedAccountsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists deleted accounts under the subscription. +// +// Generated from API version 2023-01-01 +// - options - DeletedAccountsClientListOptions contains the optional parameters for the DeletedAccountsClient.NewListPager +// method. +func (client *DeletedAccountsClient) NewListPager(options *DeletedAccountsClientListOptions) *runtime.Pager[DeletedAccountsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DeletedAccountsClientListResponse]{ + More: func(page DeletedAccountsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeletedAccountsClientListResponse) (DeletedAccountsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeletedAccountsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return DeletedAccountsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DeletedAccountsClient) listCreateRequest(ctx context.Context, options *DeletedAccountsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/deletedAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DeletedAccountsClient) listHandleResponse(resp *http.Response) (DeletedAccountsClientListResponse, error) { + result := DeletedAccountsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedAccountListResult); err != nil { + return DeletedAccountsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/encryptionscopes_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/encryptionscopes_client.go new file mode 100644 index 0000000000..1aaa4eaf0c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/encryptionscopes_client.go @@ -0,0 +1,347 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// EncryptionScopesClient contains the methods for the EncryptionScopes group. +// Don't use this type directly, use NewEncryptionScopesClient() instead. +type EncryptionScopesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewEncryptionScopesClient creates a new instance of EncryptionScopesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewEncryptionScopesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*EncryptionScopesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &EncryptionScopesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Returns the properties for the specified encryption scope. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - encryptionScopeName - The name of the encryption scope within the specified storage account. Encryption scope names must +// be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - options - EncryptionScopesClientGetOptions contains the optional parameters for the EncryptionScopesClient.Get method. +func (client *EncryptionScopesClient) Get(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *EncryptionScopesClientGetOptions) (EncryptionScopesClientGetResponse, error) { + var err error + const operationName = "EncryptionScopesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, encryptionScopeName, options) + if err != nil { + return EncryptionScopesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EncryptionScopesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EncryptionScopesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *EncryptionScopesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *EncryptionScopesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if encryptionScopeName == "" { + return nil, errors.New("parameter encryptionScopeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{encryptionScopeName}", url.PathEscape(encryptionScopeName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *EncryptionScopesClient) getHandleResponse(resp *http.Response) (EncryptionScopesClientGetResponse, error) { + result := EncryptionScopesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScope); err != nil { + return EncryptionScopesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the encryption scopes available under the specified storage account. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - EncryptionScopesClientListOptions contains the optional parameters for the EncryptionScopesClient.NewListPager +// method. +func (client *EncryptionScopesClient) NewListPager(resourceGroupName string, accountName string, options *EncryptionScopesClientListOptions) *runtime.Pager[EncryptionScopesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[EncryptionScopesClientListResponse]{ + More: func(page EncryptionScopesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *EncryptionScopesClientListResponse) (EncryptionScopesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EncryptionScopesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return EncryptionScopesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *EncryptionScopesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *EncryptionScopesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Maxpagesize != nil { + reqQP.Set("$maxpagesize", strconv.FormatInt(int64(*options.Maxpagesize), 10)) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Include != nil { + reqQP.Set("$include", string(*options.Include)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *EncryptionScopesClient) listHandleResponse(resp *http.Response) (EncryptionScopesClientListResponse, error) { + result := EncryptionScopesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScopeListResult); err != nil { + return EncryptionScopesClientListResponse{}, err + } + return result, nil +} + +// Patch - Update encryption scope properties as specified in the request body. Update fails if the specified encryption scope +// does not already exist. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - encryptionScopeName - The name of the encryption scope within the specified storage account. Encryption scope names must +// be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - encryptionScope - Encryption scope properties to be used for the update. +// - options - EncryptionScopesClientPatchOptions contains the optional parameters for the EncryptionScopesClient.Patch method. +func (client *EncryptionScopesClient) Patch(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope EncryptionScope, options *EncryptionScopesClientPatchOptions) (EncryptionScopesClientPatchResponse, error) { + var err error + const operationName = "EncryptionScopesClient.Patch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchCreateRequest(ctx, resourceGroupName, accountName, encryptionScopeName, encryptionScope, options) + if err != nil { + return EncryptionScopesClientPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EncryptionScopesClientPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EncryptionScopesClientPatchResponse{}, err + } + resp, err := client.patchHandleResponse(httpResp) + return resp, err +} + +// patchCreateRequest creates the Patch request. +func (client *EncryptionScopesClient) patchCreateRequest(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope EncryptionScope, options *EncryptionScopesClientPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if encryptionScopeName == "" { + return nil, errors.New("parameter encryptionScopeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{encryptionScopeName}", url.PathEscape(encryptionScopeName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, encryptionScope); err != nil { + return nil, err + } + return req, nil +} + +// patchHandleResponse handles the Patch response. +func (client *EncryptionScopesClient) patchHandleResponse(resp *http.Response) (EncryptionScopesClientPatchResponse, error) { + result := EncryptionScopesClientPatchResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScope); err != nil { + return EncryptionScopesClientPatchResponse{}, err + } + return result, nil +} + +// Put - Synchronously creates or updates an encryption scope under the specified storage account. If an encryption scope +// is already created and a subsequent request is issued with different properties, the +// encryption scope properties will be updated per the specified request. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - encryptionScopeName - The name of the encryption scope within the specified storage account. Encryption scope names must +// be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every +// dash (-) character must be immediately preceded and followed by a letter or number. +// - encryptionScope - Encryption scope properties to be used for the create or update. +// - options - EncryptionScopesClientPutOptions contains the optional parameters for the EncryptionScopesClient.Put method. +func (client *EncryptionScopesClient) Put(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope EncryptionScope, options *EncryptionScopesClientPutOptions) (EncryptionScopesClientPutResponse, error) { + var err error + const operationName = "EncryptionScopesClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, resourceGroupName, accountName, encryptionScopeName, encryptionScope, options) + if err != nil { + return EncryptionScopesClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EncryptionScopesClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return EncryptionScopesClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *EncryptionScopesClient) putCreateRequest(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope EncryptionScope, options *EncryptionScopesClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if encryptionScopeName == "" { + return nil, errors.New("parameter encryptionScopeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{encryptionScopeName}", url.PathEscape(encryptionScopeName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, encryptionScope); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *EncryptionScopesClient) putHandleResponse(resp *http.Response) (EncryptionScopesClientPutResponse, error) { + result := EncryptionScopesClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScope); err != nil { + return EncryptionScopesClientPutResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileservices_client.go new file mode 100644 index 0000000000..238ba98c86 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileservices_client.go @@ -0,0 +1,249 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// FileServicesClient contains the methods for the FileServices group. +// Don't use this type directly, use NewFileServicesClient() instead. +type FileServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFileServicesClient creates a new instance of FileServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewFileServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FileServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FileServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetServiceProperties - Gets the properties of file services in storage accounts, including CORS (Cross-Origin Resource +// Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - FileServicesClientGetServicePropertiesOptions contains the optional parameters for the FileServicesClient.GetServiceProperties +// method. +func (client *FileServicesClient) GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, options *FileServicesClientGetServicePropertiesOptions) (FileServicesClientGetServicePropertiesResponse, error) { + var err error + const operationName = "FileServicesClient.GetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return FileServicesClientGetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileServicesClientGetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileServicesClientGetServicePropertiesResponse{}, err + } + resp, err := client.getServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// getServicePropertiesCreateRequest creates the GetServiceProperties request. +func (client *FileServicesClient) getServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *FileServicesClientGetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/{FileServicesName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{FileServicesName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getServicePropertiesHandleResponse handles the GetServiceProperties response. +func (client *FileServicesClient) getServicePropertiesHandleResponse(resp *http.Response) (FileServicesClientGetServicePropertiesResponse, error) { + result := FileServicesClientGetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileServiceProperties); err != nil { + return FileServicesClientGetServicePropertiesResponse{}, err + } + return result, nil +} + +// List - List all file services in storage accounts +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - FileServicesClientListOptions contains the optional parameters for the FileServicesClient.List method. +func (client *FileServicesClient) List(ctx context.Context, resourceGroupName string, accountName string, options *FileServicesClientListOptions) (FileServicesClientListResponse, error) { + var err error + const operationName = "FileServicesClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return FileServicesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileServicesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileServicesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *FileServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *FileServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *FileServicesClient) listHandleResponse(resp *http.Response) (FileServicesClientListResponse, error) { + result := FileServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileServiceItems); err != nil { + return FileServicesClientListResponse{}, err + } + return result, nil +} + +// SetServiceProperties - Sets the properties of file services in storage accounts, including CORS (Cross-Origin Resource +// Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The properties of file services in storage accounts, including CORS (Cross-Origin Resource Sharing) rules. +// - options - FileServicesClientSetServicePropertiesOptions contains the optional parameters for the FileServicesClient.SetServiceProperties +// method. +func (client *FileServicesClient) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters FileServiceProperties, options *FileServicesClientSetServicePropertiesOptions) (FileServicesClientSetServicePropertiesResponse, error) { + var err error + const operationName = "FileServicesClient.SetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return FileServicesClientSetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileServicesClientSetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileServicesClientSetServicePropertiesResponse{}, err + } + resp, err := client.setServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// setServicePropertiesCreateRequest creates the SetServiceProperties request. +func (client *FileServicesClient) setServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters FileServiceProperties, options *FileServicesClientSetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/{FileServicesName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{FileServicesName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// setServicePropertiesHandleResponse handles the SetServiceProperties response. +func (client *FileServicesClient) setServicePropertiesHandleResponse(resp *http.Response) (FileServicesClientSetServicePropertiesResponse, error) { + result := FileServicesClientSetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileServiceProperties); err != nil { + return FileServicesClientSetServicePropertiesResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileshares_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileshares_client.go new file mode 100644 index 0000000000..df9e8df21b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fileshares_client.go @@ -0,0 +1,572 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// FileSharesClient contains the methods for the FileShares group. +// Don't use this type directly, use NewFileSharesClient() instead. +type FileSharesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFileSharesClient creates a new instance of FileSharesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewFileSharesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FileSharesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FileSharesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates a new share under the specified account as described by request body. The share resource includes metadata +// and properties for that share. It does not include a list of the files contained by +// the share. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - shareName - The name of the file share within the specified storage account. File share names must be between 3 and 63 +// characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) +// character must be immediately preceded and followed by a letter or number. +// - fileShare - Properties of the file share to create. +// - options - FileSharesClientCreateOptions contains the optional parameters for the FileSharesClient.Create method. +func (client *FileSharesClient) Create(ctx context.Context, resourceGroupName string, accountName string, shareName string, fileShare FileShare, options *FileSharesClientCreateOptions) (FileSharesClientCreateResponse, error) { + var err error + const operationName = "FileSharesClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, shareName, fileShare, options) + if err != nil { + return FileSharesClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileSharesClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return FileSharesClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *FileSharesClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareName string, fileShare FileShare, options *FileSharesClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if shareName == "" { + return nil, errors.New("parameter shareName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{shareName}", url.PathEscape(shareName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, fileShare); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *FileSharesClient) createHandleResponse(resp *http.Response) (FileSharesClientCreateResponse, error) { + result := FileSharesClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileShare); err != nil { + return FileSharesClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified share under its account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - shareName - The name of the file share within the specified storage account. File share names must be between 3 and 63 +// characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) +// character must be immediately preceded and followed by a letter or number. +// - options - FileSharesClientDeleteOptions contains the optional parameters for the FileSharesClient.Delete method. +func (client *FileSharesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, shareName string, options *FileSharesClientDeleteOptions) (FileSharesClientDeleteResponse, error) { + var err error + const operationName = "FileSharesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, shareName, options) + if err != nil { + return FileSharesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileSharesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return FileSharesClientDeleteResponse{}, err + } + return FileSharesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *FileSharesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareName string, options *FileSharesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if shareName == "" { + return nil, errors.New("parameter shareName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{shareName}", url.PathEscape(shareName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Include != nil { + reqQP.Set("$include", *options.Include) + } + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.XMSSnapshot != nil { + req.Raw().Header["x-ms-snapshot"] = []string{*options.XMSSnapshot} + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets properties of a specified share. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - shareName - The name of the file share within the specified storage account. File share names must be between 3 and 63 +// characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) +// character must be immediately preceded and followed by a letter or number. +// - options - FileSharesClientGetOptions contains the optional parameters for the FileSharesClient.Get method. +func (client *FileSharesClient) Get(ctx context.Context, resourceGroupName string, accountName string, shareName string, options *FileSharesClientGetOptions) (FileSharesClientGetResponse, error) { + var err error + const operationName = "FileSharesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, shareName, options) + if err != nil { + return FileSharesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileSharesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileSharesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FileSharesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareName string, options *FileSharesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if shareName == "" { + return nil, errors.New("parameter shareName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{shareName}", url.PathEscape(shareName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.XMSSnapshot != nil { + req.Raw().Header["x-ms-snapshot"] = []string{*options.XMSSnapshot} + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FileSharesClient) getHandleResponse(resp *http.Response) (FileSharesClientGetResponse, error) { + result := FileSharesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileShare); err != nil { + return FileSharesClientGetResponse{}, err + } + return result, nil +} + +// Lease - The Lease Share operation establishes and manages a lock on a share for delete operations. The lock duration can +// be 15 to 60 seconds, or can be infinite. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - shareName - The name of the file share within the specified storage account. File share names must be between 3 and 63 +// characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) +// character must be immediately preceded and followed by a letter or number. +// - options - FileSharesClientLeaseOptions contains the optional parameters for the FileSharesClient.Lease method. +func (client *FileSharesClient) Lease(ctx context.Context, resourceGroupName string, accountName string, shareName string, options *FileSharesClientLeaseOptions) (FileSharesClientLeaseResponse, error) { + var err error + const operationName = "FileSharesClient.Lease" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.leaseCreateRequest(ctx, resourceGroupName, accountName, shareName, options) + if err != nil { + return FileSharesClientLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileSharesClientLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileSharesClientLeaseResponse{}, err + } + resp, err := client.leaseHandleResponse(httpResp) + return resp, err +} + +// leaseCreateRequest creates the Lease request. +func (client *FileSharesClient) leaseCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareName string, options *FileSharesClientLeaseOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}/lease" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if shareName == "" { + return nil, errors.New("parameter shareName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{shareName}", url.PathEscape(shareName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.XMSSnapshot != nil { + req.Raw().Header["x-ms-snapshot"] = []string{*options.XMSSnapshot} + } + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Parameters != nil { + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// leaseHandleResponse handles the Lease response. +func (client *FileSharesClient) leaseHandleResponse(resp *http.Response) (FileSharesClientLeaseResponse, error) { + result := FileSharesClientLeaseResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.LeaseShareResponse); err != nil { + return FileSharesClientLeaseResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all shares. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - FileSharesClientListOptions contains the optional parameters for the FileSharesClient.NewListPager method. +func (client *FileSharesClient) NewListPager(resourceGroupName string, accountName string, options *FileSharesClientListOptions) *runtime.Pager[FileSharesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[FileSharesClientListResponse]{ + More: func(page FileSharesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FileSharesClientListResponse) (FileSharesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FileSharesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return FileSharesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *FileSharesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *FileSharesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Maxpagesize != nil { + reqQP.Set("$maxpagesize", *options.Maxpagesize) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *FileSharesClient) listHandleResponse(resp *http.Response) (FileSharesClientListResponse, error) { + result := FileSharesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileShareItems); err != nil { + return FileSharesClientListResponse{}, err + } + return result, nil +} + +// Restore - Restore a file share within a valid retention days if share soft delete is enabled +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - shareName - The name of the file share within the specified storage account. File share names must be between 3 and 63 +// characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) +// character must be immediately preceded and followed by a letter or number. +// - options - FileSharesClientRestoreOptions contains the optional parameters for the FileSharesClient.Restore method. +func (client *FileSharesClient) Restore(ctx context.Context, resourceGroupName string, accountName string, shareName string, deletedShare DeletedShare, options *FileSharesClientRestoreOptions) (FileSharesClientRestoreResponse, error) { + var err error + const operationName = "FileSharesClient.Restore" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restoreCreateRequest(ctx, resourceGroupName, accountName, shareName, deletedShare, options) + if err != nil { + return FileSharesClientRestoreResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileSharesClientRestoreResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileSharesClientRestoreResponse{}, err + } + return FileSharesClientRestoreResponse{}, nil +} + +// restoreCreateRequest creates the Restore request. +func (client *FileSharesClient) restoreCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareName string, deletedShare DeletedShare, options *FileSharesClientRestoreOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}/restore" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if shareName == "" { + return nil, errors.New("parameter shareName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{shareName}", url.PathEscape(shareName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, deletedShare); err != nil { + return nil, err + } + return req, nil +} + +// Update - Updates share properties as specified in request body. Properties not mentioned in the request will not be changed. +// Update fails if the specified share does not already exist. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - shareName - The name of the file share within the specified storage account. File share names must be between 3 and 63 +// characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) +// character must be immediately preceded and followed by a letter or number. +// - fileShare - Properties to update for the file share. +// - options - FileSharesClientUpdateOptions contains the optional parameters for the FileSharesClient.Update method. +func (client *FileSharesClient) Update(ctx context.Context, resourceGroupName string, accountName string, shareName string, fileShare FileShare, options *FileSharesClientUpdateOptions) (FileSharesClientUpdateResponse, error) { + var err error + const operationName = "FileSharesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, shareName, fileShare, options) + if err != nil { + return FileSharesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FileSharesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FileSharesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *FileSharesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareName string, fileShare FileShare, options *FileSharesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/default/shares/{shareName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if shareName == "" { + return nil, errors.New("parameter shareName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{shareName}", url.PathEscape(shareName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, fileShare); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *FileSharesClient) updateHandleResponse(resp *http.Response) (FileSharesClientUpdateResponse, error) { + result := FileSharesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FileShare); err != nil { + return FileSharesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/localusers_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/localusers_client.go new file mode 100644 index 0000000000..614a876e45 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/localusers_client.go @@ -0,0 +1,461 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LocalUsersClient contains the methods for the LocalUsers group. +// Don't use this type directly, use NewLocalUsersClient() instead. +type LocalUsersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLocalUsersClient creates a new instance of LocalUsersClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewLocalUsersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LocalUsersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LocalUsersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update the properties of a local user associated with the storage account +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - username - The name of local user. The username must contain lowercase letters and numbers only. It must be unique only +// within the storage account. +// - properties - The local user associated with a storage account. +// - options - LocalUsersClientCreateOrUpdateOptions contains the optional parameters for the LocalUsersClient.CreateOrUpdate +// method. +func (client *LocalUsersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, username string, properties LocalUser, options *LocalUsersClientCreateOrUpdateOptions) (LocalUsersClientCreateOrUpdateResponse, error) { + var err error + const operationName = "LocalUsersClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, username, properties, options) + if err != nil { + return LocalUsersClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalUsersClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocalUsersClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *LocalUsersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, username string, properties LocalUser, options *LocalUsersClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if username == "" { + return nil, errors.New("parameter username cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{username}", url.PathEscape(username)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *LocalUsersClient) createOrUpdateHandleResponse(resp *http.Response) (LocalUsersClientCreateOrUpdateResponse, error) { + result := LocalUsersClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalUser); err != nil { + return LocalUsersClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the local user associated with the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - username - The name of local user. The username must contain lowercase letters and numbers only. It must be unique only +// within the storage account. +// - options - LocalUsersClientDeleteOptions contains the optional parameters for the LocalUsersClient.Delete method. +func (client *LocalUsersClient) Delete(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientDeleteOptions) (LocalUsersClientDeleteResponse, error) { + var err error + const operationName = "LocalUsersClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, username, options) + if err != nil { + return LocalUsersClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalUsersClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return LocalUsersClientDeleteResponse{}, err + } + return LocalUsersClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LocalUsersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if username == "" { + return nil, errors.New("parameter username cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{username}", url.PathEscape(username)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get the local user of the storage account by username. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - username - The name of local user. The username must contain lowercase letters and numbers only. It must be unique only +// within the storage account. +// - options - LocalUsersClientGetOptions contains the optional parameters for the LocalUsersClient.Get method. +func (client *LocalUsersClient) Get(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientGetOptions) (LocalUsersClientGetResponse, error) { + var err error + const operationName = "LocalUsersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, username, options) + if err != nil { + return LocalUsersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalUsersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocalUsersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LocalUsersClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if username == "" { + return nil, errors.New("parameter username cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{username}", url.PathEscape(username)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LocalUsersClient) getHandleResponse(resp *http.Response) (LocalUsersClientGetResponse, error) { + result := LocalUsersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalUser); err != nil { + return LocalUsersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List the local users associated with the storage account. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - LocalUsersClientListOptions contains the optional parameters for the LocalUsersClient.NewListPager method. +func (client *LocalUsersClient) NewListPager(resourceGroupName string, accountName string, options *LocalUsersClientListOptions) *runtime.Pager[LocalUsersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LocalUsersClientListResponse]{ + More: func(page LocalUsersClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *LocalUsersClientListResponse) (LocalUsersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LocalUsersClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return LocalUsersClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalUsersClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return LocalUsersClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LocalUsersClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *LocalUsersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LocalUsersClient) listHandleResponse(resp *http.Response) (LocalUsersClientListResponse, error) { + result := LocalUsersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalUsers); err != nil { + return LocalUsersClientListResponse{}, err + } + return result, nil +} + +// ListKeys - List SSH authorized keys and shared key of the local user. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - username - The name of local user. The username must contain lowercase letters and numbers only. It must be unique only +// within the storage account. +// - options - LocalUsersClientListKeysOptions contains the optional parameters for the LocalUsersClient.ListKeys method. +func (client *LocalUsersClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientListKeysOptions) (LocalUsersClientListKeysResponse, error) { + var err error + const operationName = "LocalUsersClient.ListKeys" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, accountName, username, options) + if err != nil { + return LocalUsersClientListKeysResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalUsersClientListKeysResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocalUsersClientListKeysResponse{}, err + } + resp, err := client.listKeysHandleResponse(httpResp) + return resp, err +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *LocalUsersClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if username == "" { + return nil, errors.New("parameter username cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{username}", url.PathEscape(username)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *LocalUsersClient) listKeysHandleResponse(resp *http.Response) (LocalUsersClientListKeysResponse, error) { + result := LocalUsersClientListKeysResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalUserKeys); err != nil { + return LocalUsersClientListKeysResponse{}, err + } + return result, nil +} + +// RegeneratePassword - Regenerate the local user SSH password. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - username - The name of local user. The username must contain lowercase letters and numbers only. It must be unique only +// within the storage account. +// - options - LocalUsersClientRegeneratePasswordOptions contains the optional parameters for the LocalUsersClient.RegeneratePassword +// method. +func (client *LocalUsersClient) RegeneratePassword(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientRegeneratePasswordOptions) (LocalUsersClientRegeneratePasswordResponse, error) { + var err error + const operationName = "LocalUsersClient.RegeneratePassword" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.regeneratePasswordCreateRequest(ctx, resourceGroupName, accountName, username, options) + if err != nil { + return LocalUsersClientRegeneratePasswordResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocalUsersClientRegeneratePasswordResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocalUsersClientRegeneratePasswordResponse{}, err + } + resp, err := client.regeneratePasswordHandleResponse(httpResp) + return resp, err +} + +// regeneratePasswordCreateRequest creates the RegeneratePassword request. +func (client *LocalUsersClient) regeneratePasswordCreateRequest(ctx context.Context, resourceGroupName string, accountName string, username string, options *LocalUsersClientRegeneratePasswordOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}/regeneratePassword" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if username == "" { + return nil, errors.New("parameter username cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{username}", url.PathEscape(username)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// regeneratePasswordHandleResponse handles the RegeneratePassword response. +func (client *LocalUsersClient) regeneratePasswordHandleResponse(resp *http.Response) (LocalUsersClientRegeneratePasswordResponse, error) { + result := LocalUsersClientRegeneratePasswordResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocalUserRegeneratePasswordResult); err != nil { + return LocalUsersClientRegeneratePasswordResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/managementpolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/managementpolicies_client.go new file mode 100644 index 0000000000..4f3f96365a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/managementpolicies_client.go @@ -0,0 +1,249 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ManagementPoliciesClient contains the methods for the ManagementPolicies group. +// Don't use this type directly, use NewManagementPoliciesClient() instead. +type ManagementPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagementPoliciesClient creates a new instance of ManagementPoliciesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewManagementPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagementPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagementPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Sets the managementpolicy to the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - managementPolicyName - The name of the Storage Account Management Policy. It should always be 'default' +// - properties - The ManagementPolicy set to a storage account. +// - options - ManagementPoliciesClientCreateOrUpdateOptions contains the optional parameters for the ManagementPoliciesClient.CreateOrUpdate +// method. +func (client *ManagementPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, managementPolicyName ManagementPolicyName, properties ManagementPolicy, options *ManagementPoliciesClientCreateOrUpdateOptions) (ManagementPoliciesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ManagementPoliciesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, managementPolicyName, properties, options) + if err != nil { + return ManagementPoliciesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementPoliciesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementPoliciesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ManagementPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managementPolicyName ManagementPolicyName, properties ManagementPolicy, options *ManagementPoliciesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/managementPolicies/{managementPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if managementPolicyName == "" { + return nil, errors.New("parameter managementPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementPolicyName}", url.PathEscape(string(managementPolicyName))) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ManagementPoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (ManagementPoliciesClientCreateOrUpdateResponse, error) { + result := ManagementPoliciesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagementPolicy); err != nil { + return ManagementPoliciesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the managementpolicy associated with the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - managementPolicyName - The name of the Storage Account Management Policy. It should always be 'default' +// - options - ManagementPoliciesClientDeleteOptions contains the optional parameters for the ManagementPoliciesClient.Delete +// method. +func (client *ManagementPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, managementPolicyName ManagementPolicyName, options *ManagementPoliciesClientDeleteOptions) (ManagementPoliciesClientDeleteResponse, error) { + var err error + const operationName = "ManagementPoliciesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, managementPolicyName, options) + if err != nil { + return ManagementPoliciesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementPoliciesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ManagementPoliciesClientDeleteResponse{}, err + } + return ManagementPoliciesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ManagementPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managementPolicyName ManagementPolicyName, options *ManagementPoliciesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/managementPolicies/{managementPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if managementPolicyName == "" { + return nil, errors.New("parameter managementPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementPolicyName}", url.PathEscape(string(managementPolicyName))) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Gets the managementpolicy associated with the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - managementPolicyName - The name of the Storage Account Management Policy. It should always be 'default' +// - options - ManagementPoliciesClientGetOptions contains the optional parameters for the ManagementPoliciesClient.Get method. +func (client *ManagementPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, managementPolicyName ManagementPolicyName, options *ManagementPoliciesClientGetOptions) (ManagementPoliciesClientGetResponse, error) { + var err error + const operationName = "ManagementPoliciesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, managementPolicyName, options) + if err != nil { + return ManagementPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagementPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managementPolicyName ManagementPolicyName, options *ManagementPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/managementPolicies/{managementPolicyName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if managementPolicyName == "" { + return nil, errors.New("parameter managementPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementPolicyName}", url.PathEscape(string(managementPolicyName))) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagementPoliciesClient) getHandleResponse(resp *http.Response) (ManagementPoliciesClientGetResponse, error) { + result := ManagementPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagementPolicy); err != nil { + return ManagementPoliciesClientGetResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models.go new file mode 100644 index 0000000000..3a9b23aabe --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models.go @@ -0,0 +1,2832 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import "time" + +type AccessPolicy struct { + // Expiry time of the access policy + ExpiryTime *time.Time + + // List of abbreviated permissions. + Permission *string + + // Start time of the access policy + StartTime *time.Time +} + +// Account - The storage account. +type Account struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The extendedLocation of the resource. + ExtendedLocation *ExtendedLocation + + // The identity of the resource. + Identity *Identity + + // Properties of the storage account. + Properties *AccountProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; Gets the Kind. + Kind *Kind + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Gets the SKU. + SKU *SKU + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AccountCheckNameAvailabilityParameters - The parameters used to check the availability of the storage account name. +type AccountCheckNameAvailabilityParameters struct { + // REQUIRED; The storage account name. + Name *string + + // CONSTANT; The type of resource, Microsoft.Storage/storageAccounts + // Field has constant value "Microsoft.Storage/storageAccounts", any specified value is ignored. + Type *string +} + +// AccountCreateParameters - The parameters used when creating a storage account. +type AccountCreateParameters struct { + // REQUIRED; Required. Indicates the type of storage account. + Kind *Kind + + // REQUIRED; Required. Gets or sets the location of the resource. This will be one of the supported and registered Azure Geo + // Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource + // cannot be changed once it is created, but if an identical geo region is specified on update, the request will succeed. + Location *string + + // REQUIRED; Required. Gets or sets the SKU name. + SKU *SKU + + // Optional. Set the extended location of the resource. If not set, the storage account will be created in Azure main region. + // Otherwise it will be created in the specified extended location + ExtendedLocation *ExtendedLocation + + // The identity of the resource. + Identity *Identity + + // The parameters used to create the storage account. + Properties *AccountPropertiesCreateParameters + + // Gets or sets a list of key value pairs that describe the resource. These tags can be used for viewing and grouping this + // resource (across resource groups). A maximum of 15 tags can be provided for a + // resource. Each tag must have a key with a length no greater than 128 characters and a value with a length no greater than + // 256 characters. + Tags map[string]*string +} + +// AccountImmutabilityPolicyProperties - This defines account-level immutability policy properties. +type AccountImmutabilityPolicyProperties struct { + // This property can only be changed for disabled and unlocked time-based retention policies. When enabled, new blocks can + // be written to an append blob while maintaining immutability protection and + // compliance. Only new blocks can be added and any existing blocks cannot be modified or deleted. + AllowProtectedAppendWrites *bool + + // The immutability period for the blobs in the container since the policy creation, in days. + ImmutabilityPeriodSinceCreationInDays *int32 + + // The ImmutabilityPolicy state defines the mode of the policy. Disabled state disables the policy, Unlocked state allows + // increase and decrease of immutability retention time and also allows toggling + // allowProtectedAppendWrites property, Locked state only allows the increase of the immutability retention time. A policy + // can only be created in a Disabled or Unlocked state and can be toggled between + // the two states. Only a policy in an Unlocked state can transition to a Locked state which cannot be reverted. + State *AccountImmutabilityPolicyState +} + +// AccountInternetEndpoints - The URIs that are used to perform a retrieval of a public blob, file, web or dfs object via +// a internet routing endpoint. +type AccountInternetEndpoints struct { + // READ-ONLY; Gets the blob endpoint. + Blob *string + + // READ-ONLY; Gets the dfs endpoint. + Dfs *string + + // READ-ONLY; Gets the file endpoint. + File *string + + // READ-ONLY; Gets the web endpoint. + Web *string +} + +// AccountKey - An access key for the storage account. +type AccountKey struct { + // READ-ONLY; Creation time of the key, in round trip date format. + CreationTime *time.Time + + // READ-ONLY; Name of the key. + KeyName *string + + // READ-ONLY; Permissions for the key -- read-only or full permissions. + Permissions *KeyPermission + + // READ-ONLY; Base 64-encoded value of the key. + Value *string +} + +// AccountListKeysResult - The response from the ListKeys operation. +type AccountListKeysResult struct { + // READ-ONLY; Gets the list of storage account keys and their properties for the specified storage account. + Keys []*AccountKey +} + +// AccountListResult - The response from the List Storage Accounts operation. +type AccountListResult struct { + // READ-ONLY; Request URL that can be used to query next page of storage accounts. Returned when total number of requested + // storage accounts exceed maximum page size. + NextLink *string + + // READ-ONLY; Gets the list of storage accounts and their properties. + Value []*Account +} + +// AccountMicrosoftEndpoints - The URIs that are used to perform a retrieval of a public blob, queue, table, web or dfs object +// via a microsoft routing endpoint. +type AccountMicrosoftEndpoints struct { + // READ-ONLY; Gets the blob endpoint. + Blob *string + + // READ-ONLY; Gets the dfs endpoint. + Dfs *string + + // READ-ONLY; Gets the file endpoint. + File *string + + // READ-ONLY; Gets the queue endpoint. + Queue *string + + // READ-ONLY; Gets the table endpoint. + Table *string + + // READ-ONLY; Gets the web endpoint. + Web *string +} + +// AccountMigration - The parameters or status associated with an ongoing or enqueued storage account migration in order to +// update its current SKU or region. +type AccountMigration struct { + // REQUIRED; The properties of a storage account’s ongoing or enqueued migration. + StorageAccountMigrationDetails *AccountMigrationProperties + + // current value is 'default' for customer initiated migration + Name *string + + // SrpAccountMigrationType in ARM contract which is 'accountMigrations' + Type *string + + // READ-ONLY; Migration Resource Id + ID *string +} + +// AccountMigrationProperties - The properties of a storage account’s ongoing or enqueued migration. +type AccountMigrationProperties struct { + // REQUIRED; Target sku name for the account + TargetSKUName *SKUName + + // READ-ONLY; Reason for migration failure + MigrationFailedDetailedReason *string + + // READ-ONLY; Error code for migration failure + MigrationFailedReason *string + + // READ-ONLY; Current status of migration + MigrationStatus *MigrationStatus +} + +// AccountProperties - Properties of the storage account. +type AccountProperties struct { + // Allow or disallow public access to all blobs or containers in the storage account. The default interpretation is false + // for this property. + AllowBlobPublicAccess *bool + + // Allow or disallow cross AAD tenant object replication. Set this property to true for new or existing accounts only if object + // replication policies will involve storage accounts in different AAD + // tenants. The default interpretation is false for new accounts to follow best security practices by default. + AllowCrossTenantReplication *bool + + // Indicates whether the storage account permits requests to be authorized with the account access key via Shared Key. If + // false, then all requests, including shared access signatures, must be authorized + // with Azure Active Directory (Azure AD). The default value is null, which is equivalent to true. + AllowSharedKeyAccess *bool + + // Restrict copy to and from Storage Accounts within an AAD tenant or with Private Links to the same VNet. + AllowedCopyScope *AllowedCopyScope + + // Provides the identity based authentication settings for Azure Files. + AzureFilesIdentityBasedAuthentication *AzureFilesIdentityBasedAuthentication + + // Allows you to specify the type of endpoint. Set this to AzureDNSZone to create a large number of accounts in a single subscription, + // which creates accounts in an Azure DNS Zone and the endpoint URL + // will have an alphanumeric DNS Zone identifier. + DNSEndpointType *DNSEndpointType + + // A boolean flag which indicates whether the default authentication is OAuth or not. The default interpretation is false + // for this property. + DefaultToOAuthAuthentication *bool + + // Allows https traffic only to storage service if sets to true. + EnableHTTPSTrafficOnly *bool + + // NFS 3.0 protocol support enabled if set to true. + EnableNfsV3 *bool + + // The property is immutable and can only be set to true at the account creation time. When set to true, it enables object + // level immutability for all the containers in the account by default. + ImmutableStorageWithVersioning *ImmutableStorageAccount + + // Account HierarchicalNamespace enabled if sets to true. + IsHnsEnabled *bool + + // Enables local users feature, if set to true + IsLocalUserEnabled *bool + + // Enables Secure File Transfer Protocol, if set to true + IsSftpEnabled *bool + + // Allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. + LargeFileSharesState *LargeFileSharesState + + // Set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property. + MinimumTLSVersion *MinimumTLSVersion + + // Allow or disallow public network access to Storage Account. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. + PublicNetworkAccess *PublicNetworkAccess + + // Maintains information about the network routing choice opted by the user for data transfer + RoutingPreference *RoutingPreference + + // This property is readOnly and is set by server during asynchronous storage account sku conversion operations. + StorageAccountSKUConversionStatus *AccountSKUConversionStatus + + // READ-ONLY; Required for storage accounts where kind = BlobStorage. The access tier is used for billing. The 'Premium' access + // tier is the default value for premium block blobs storage account type and it cannot + // be changed for the premium block blobs storage account type. + AccessTier *AccessTier + + // READ-ONLY; If customer initiated account migration is in progress, the value will be true else it will be null. + AccountMigrationInProgress *bool + + // READ-ONLY; Blob restore status + BlobRestoreStatus *BlobRestoreStatus + + // READ-ONLY; Gets the creation date and time of the storage account in UTC. + CreationTime *time.Time + + // READ-ONLY; Gets the custom domain the user assigned to this storage account. + CustomDomain *CustomDomain + + // READ-ONLY; Encryption settings to be used for server-side encryption for the storage account. + Encryption *Encryption + + // READ-ONLY; If the failover is in progress, the value will be true, otherwise, it will be null. + FailoverInProgress *bool + + // READ-ONLY; Geo Replication Stats + GeoReplicationStats *GeoReplicationStats + + // READ-ONLY; This property will be set to true or false on an event of ongoing migration. Default value is null. + IsSKUConversionBlocked *bool + + // READ-ONLY; Storage account keys creation time. + KeyCreationTime *KeyCreationTime + + // READ-ONLY; KeyPolicy assigned to the storage account. + KeyPolicy *KeyPolicy + + // READ-ONLY; Gets the timestamp of the most recent instance of a failover to the secondary location. Only the most recent + // timestamp is retained. This element is not returned if there has never been a failover + // instance. Only available if the accountType is StandardGRS or StandardRAGRS. + LastGeoFailoverTime *time.Time + + // READ-ONLY; Network rule set + NetworkRuleSet *NetworkRuleSet + + // READ-ONLY; Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object. Note that StandardZRS + // and PremiumLRS accounts only return the blob endpoint. + PrimaryEndpoints *Endpoints + + // READ-ONLY; Gets the location of the primary data center for the storage account. + PrimaryLocation *string + + // READ-ONLY; List of private endpoint connection associated with the specified storage account + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; Gets the status of the storage account at the time the operation was called. + ProvisioningState *ProvisioningState + + // READ-ONLY; SasPolicy assigned to the storage account. + SasPolicy *SasPolicy + + // READ-ONLY; Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object from the secondary + // location of the storage account. Only available if the SKU name is Standard_RAGRS. + SecondaryEndpoints *Endpoints + + // READ-ONLY; Gets the location of the geo-replicated secondary for the storage account. Only available if the accountType + // is StandardGRS or StandardRAGRS. + SecondaryLocation *string + + // READ-ONLY; Gets the status indicating whether the primary location of the storage account is available or unavailable. + StatusOfPrimary *AccountStatus + + // READ-ONLY; Gets the status indicating whether the secondary location of the storage account is available or unavailable. + // Only available if the SKU name is StandardGRS or StandardRAGRS. + StatusOfSecondary *AccountStatus +} + +// AccountPropertiesCreateParameters - The parameters used to create the storage account. +type AccountPropertiesCreateParameters struct { + // Required for storage accounts where kind = BlobStorage. The access tier is used for billing. The 'Premium' access tier + // is the default value for premium block blobs storage account type and it cannot + // be changed for the premium block blobs storage account type. + AccessTier *AccessTier + + // Allow or disallow public access to all blobs or containers in the storage account. The default interpretation is false + // for this property. + AllowBlobPublicAccess *bool + + // Allow or disallow cross AAD tenant object replication. Set this property to true for new or existing accounts only if object + // replication policies will involve storage accounts in different AAD + // tenants. The default interpretation is false for new accounts to follow best security practices by default. + AllowCrossTenantReplication *bool + + // Indicates whether the storage account permits requests to be authorized with the account access key via Shared Key. If + // false, then all requests, including shared access signatures, must be authorized + // with Azure Active Directory (Azure AD). The default value is null, which is equivalent to true. + AllowSharedKeyAccess *bool + + // Restrict copy to and from Storage Accounts within an AAD tenant or with Private Links to the same VNet. + AllowedCopyScope *AllowedCopyScope + + // Provides the identity based authentication settings for Azure Files. + AzureFilesIdentityBasedAuthentication *AzureFilesIdentityBasedAuthentication + + // User domain assigned to the storage account. Name is the CNAME source. Only one custom domain is supported per storage + // account at this time. To clear the existing custom domain, use an empty string + // for the custom domain name property. + CustomDomain *CustomDomain + + // Allows you to specify the type of endpoint. Set this to AzureDNSZone to create a large number of accounts in a single subscription, + // which creates accounts in an Azure DNS Zone and the endpoint URL + // will have an alphanumeric DNS Zone identifier. + DNSEndpointType *DNSEndpointType + + // A boolean flag which indicates whether the default authentication is OAuth or not. The default interpretation is false + // for this property. + DefaultToOAuthAuthentication *bool + + // Allows https traffic only to storage service if sets to true. The default value is true since API version 2019-04-01. + EnableHTTPSTrafficOnly *bool + + // NFS 3.0 protocol support enabled if set to true. + EnableNfsV3 *bool + + // Encryption settings to be used for server-side encryption for the storage account. + Encryption *Encryption + + // The property is immutable and can only be set to true at the account creation time. When set to true, it enables object + // level immutability for all the new containers in the account by default. + ImmutableStorageWithVersioning *ImmutableStorageAccount + + // Account HierarchicalNamespace enabled if sets to true. + IsHnsEnabled *bool + + // Enables local users feature, if set to true + IsLocalUserEnabled *bool + + // Enables Secure File Transfer Protocol, if set to true + IsSftpEnabled *bool + + // KeyPolicy assigned to the storage account. + KeyPolicy *KeyPolicy + + // Allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. + LargeFileSharesState *LargeFileSharesState + + // Set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property. + MinimumTLSVersion *MinimumTLSVersion + + // Network rule set + NetworkRuleSet *NetworkRuleSet + + // Allow or disallow public network access to Storage Account. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. + PublicNetworkAccess *PublicNetworkAccess + + // Maintains information about the network routing choice opted by the user for data transfer + RoutingPreference *RoutingPreference + + // SasPolicy assigned to the storage account. + SasPolicy *SasPolicy +} + +// AccountPropertiesUpdateParameters - The parameters used when updating a storage account. +type AccountPropertiesUpdateParameters struct { + // Required for storage accounts where kind = BlobStorage. The access tier is used for billing. The 'Premium' access tier + // is the default value for premium block blobs storage account type and it cannot + // be changed for the premium block blobs storage account type. + AccessTier *AccessTier + + // Allow or disallow public access to all blobs or containers in the storage account. The default interpretation is false + // for this property. + AllowBlobPublicAccess *bool + + // Allow or disallow cross AAD tenant object replication. Set this property to true for new or existing accounts only if object + // replication policies will involve storage accounts in different AAD + // tenants. The default interpretation is false for new accounts to follow best security practices by default. + AllowCrossTenantReplication *bool + + // Indicates whether the storage account permits requests to be authorized with the account access key via Shared Key. If + // false, then all requests, including shared access signatures, must be authorized + // with Azure Active Directory (Azure AD). The default value is null, which is equivalent to true. + AllowSharedKeyAccess *bool + + // Restrict copy to and from Storage Accounts within an AAD tenant or with Private Links to the same VNet. + AllowedCopyScope *AllowedCopyScope + + // Provides the identity based authentication settings for Azure Files. + AzureFilesIdentityBasedAuthentication *AzureFilesIdentityBasedAuthentication + + // Custom domain assigned to the storage account by the user. Name is the CNAME source. Only one custom domain is supported + // per storage account at this time. To clear the existing custom domain, use an + // empty string for the custom domain name property. + CustomDomain *CustomDomain + + // Allows you to specify the type of endpoint. Set this to AzureDNSZone to create a large number of accounts in a single subscription, + // which creates accounts in an Azure DNS Zone and the endpoint URL + // will have an alphanumeric DNS Zone identifier. + DNSEndpointType *DNSEndpointType + + // A boolean flag which indicates whether the default authentication is OAuth or not. The default interpretation is false + // for this property. + DefaultToOAuthAuthentication *bool + + // Allows https traffic only to storage service if sets to true. + EnableHTTPSTrafficOnly *bool + + // Not applicable. Azure Storage encryption at rest is enabled by default for all storage accounts and cannot be disabled. + Encryption *Encryption + + // The property is immutable and can only be set to true at the account creation time. When set to true, it enables object + // level immutability for all the containers in the account by default. + ImmutableStorageWithVersioning *ImmutableStorageAccount + + // Enables local users feature, if set to true + IsLocalUserEnabled *bool + + // Enables Secure File Transfer Protocol, if set to true + IsSftpEnabled *bool + + // KeyPolicy assigned to the storage account. + KeyPolicy *KeyPolicy + + // Allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. + LargeFileSharesState *LargeFileSharesState + + // Set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property. + MinimumTLSVersion *MinimumTLSVersion + + // Network rule set + NetworkRuleSet *NetworkRuleSet + + // Allow or disallow public network access to Storage Account. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. + PublicNetworkAccess *PublicNetworkAccess + + // Maintains information about the network routing choice opted by the user for data transfer + RoutingPreference *RoutingPreference + + // SasPolicy assigned to the storage account. + SasPolicy *SasPolicy +} + +// AccountRegenerateKeyParameters - The parameters used to regenerate the storage account key. +type AccountRegenerateKeyParameters struct { + // REQUIRED; The name of storage keys that want to be regenerated, possible values are key1, key2, kerb1, kerb2. + KeyName *string +} + +// AccountSKUConversionStatus - This defines the sku conversion status object for asynchronous sku conversions. +type AccountSKUConversionStatus struct { + // This property represents the target sku name to which the account sku is being converted asynchronously. + TargetSKUName *SKUName + + // READ-ONLY; This property represents the sku conversion end time. + EndTime *string + + // READ-ONLY; This property indicates the current sku conversion status. + SKUConversionStatus *SKUConversionStatus + + // READ-ONLY; This property represents the sku conversion start time. + StartTime *string +} + +// AccountSasParameters - The parameters to list SAS credentials of a storage account. +type AccountSasParameters struct { + // REQUIRED; The signed permissions for the account SAS. Possible values include: Read (r), Write (w), Delete (d), List (l), + // Add (a), Create (c), Update (u) and Process (p). + Permissions *Permissions + + // REQUIRED; The signed resource types that are accessible with the account SAS. Service (s): Access to service-level APIs; + // Container (c): Access to container-level APIs; Object (o): Access to object-level APIs + // for blobs, queue messages, table entities, and files. + ResourceTypes *SignedResourceTypes + + // REQUIRED; The signed services accessible with the account SAS. Possible values include: Blob (b), Queue (q), Table (t), + // File (f). + Services *Services + + // REQUIRED; The time at which the shared access signature becomes invalid. + SharedAccessExpiryTime *time.Time + + // An IP address or a range of IP addresses from which to accept requests. + IPAddressOrRange *string + + // The key to sign the account SAS token with. + KeyToSign *string + + // The protocol permitted for a request made with the account SAS. + Protocols *HTTPProtocol + + // The time at which the SAS becomes valid. + SharedAccessStartTime *time.Time +} + +// AccountUpdateParameters - The parameters that can be provided when updating the storage account properties. +type AccountUpdateParameters struct { + // The identity of the resource. + Identity *Identity + + // Optional. Indicates the type of storage account. Currently only StorageV2 value supported by server. + Kind *Kind + + // The parameters used when updating a storage account. + Properties *AccountPropertiesUpdateParameters + + // Gets or sets the SKU name. Note that the SKU name cannot be updated to StandardZRS, PremiumLRS or Premium_ZRS, nor can + // accounts of those SKU names be updated to any other value. + SKU *SKU + + // Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this + // resource (across resource groups). A maximum of 15 tags can be provided for a + // resource. Each tag must have a key no greater in length than 128 characters and a value no greater in length than 256 characters. + Tags map[string]*string +} + +// ActiveDirectoryProperties - Settings properties for Active Directory (AD). +type ActiveDirectoryProperties struct { + // REQUIRED; Specifies the domain GUID. + DomainGUID *string + + // REQUIRED; Specifies the primary domain that the AD DNS server is authoritative for. + DomainName *string + + // Specifies the Active Directory account type for Azure Storage. + AccountType *ActiveDirectoryPropertiesAccountType + + // Specifies the security identifier (SID) for Azure Storage. + AzureStorageSid *string + + // Specifies the security identifier (SID). + DomainSid *string + + // Specifies the Active Directory forest to get. + ForestName *string + + // Specifies the NetBIOS domain name. + NetBiosDomainName *string + + // Specifies the Active Directory SAMAccountName for Azure Storage. + SamAccountName *string +} + +// AzureEntityResource - The resource model definition for an Azure Resource Manager resource with an etag. +type AzureEntityResource struct { + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AzureFilesIdentityBasedAuthentication - Settings for Azure Files identity based authentication. +type AzureFilesIdentityBasedAuthentication struct { + // REQUIRED; Indicates the directory service used. Note that this enum may be extended in the future. + DirectoryServiceOptions *DirectoryServiceOptions + + // Required if directoryServiceOptions are AD, optional if they are AADKERB. + ActiveDirectoryProperties *ActiveDirectoryProperties + + // Default share permission for users using Kerberos authentication if RBAC role is not assigned. + DefaultSharePermission *DefaultSharePermission +} + +// BlobContainer - Properties of the blob container, including Id, resource name, resource type, Etag. +type BlobContainer struct { + // Properties of the blob container. + ContainerProperties *ContainerProperties + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// BlobInventoryCreationTime - This property defines the creation time based filtering condition. Blob Inventory schema parameter +// 'Creation-Time' is mandatory with this filter. +type BlobInventoryCreationTime struct { + // When set the policy filters the objects that are created in the last N days. Where N is an integer value between 1 to 36500. + LastNDays *int32 +} + +// BlobInventoryPolicy - The storage account blob inventory policy. +type BlobInventoryPolicy struct { + // Returns the storage account blob inventory policy rules. + Properties *BlobInventoryPolicyProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// BlobInventoryPolicyDefinition - An object that defines the blob inventory rule. +type BlobInventoryPolicyDefinition struct { + // REQUIRED; This is a required field, it specifies the format for the inventory files. + Format *Format + + // REQUIRED; This is a required field. This field specifies the scope of the inventory created either at the blob or container + // level. + ObjectType *ObjectType + + // REQUIRED; This is a required field. This field is used to schedule an inventory formation. + Schedule *Schedule + + // REQUIRED; This is a required field. This field specifies the fields and properties of the object to be included in the + // inventory. The Schema field value 'Name' is always required. The valid values for this + // field for the 'Blob' definition.objectType include 'Name, Creation-Time, Last-Modified, Content-Length, Content-MD5, BlobType, + // AccessTier, AccessTierChangeTime, AccessTierInferred, Tags, Expiry-Time, + // hdiisfolder, Owner, Group, Permissions, Acl, Snapshot, VersionId, IsCurrentVersion, Metadata, LastAccessTime, Tags, Etag, + // ContentType, ContentEncoding, ContentLanguage, ContentCRC64, CacheControl, + // ContentDisposition, LeaseStatus, LeaseState, LeaseDuration, ServerEncrypted, Deleted, DeletionId, DeletedTime, RemainingRetentionDays, + // ImmutabilityPolicyUntilDate, ImmutabilityPolicyMode, LegalHold, + // CopyId, CopyStatus, CopySource, CopyProgress, CopyCompletionTime, CopyStatusDescription, CustomerProvidedKeySha256, RehydratePriority, + // ArchiveStatus, XmsBlobSequenceNumber, EncryptionScope, + // IncrementalCopy, TagCount'. For Blob object type schema field value 'DeletedTime' is applicable only for Hns enabled accounts. + // The valid values for 'Container' definition.objectType include 'Name, + // Last-Modified, Metadata, LeaseStatus, LeaseState, LeaseDuration, PublicAccess, HasImmutabilityPolicy, HasLegalHold, Etag, + // DefaultEncryptionScope, DenyEncryptionScopeOverride, + // ImmutableStorageWithVersioningEnabled, Deleted, Version, DeletedTime, RemainingRetentionDays'. Schema field values 'Expiry-Time, + // hdiisfolder, Owner, Group, Permissions, Acl, DeletionId' are valid only + // for Hns enabled accounts.Schema field values 'Tags, TagCount' are only valid for Non-Hns accounts. + SchemaFields []*string + + // An object that defines the filter set. + Filters *BlobInventoryPolicyFilter +} + +// BlobInventoryPolicyFilter - An object that defines the blob inventory rule filter conditions. For 'Blob' definition.objectType +// all filter properties are applicable, 'blobTypes' is required and others are optional. For +// 'Container' definition.objectType only prefixMatch is applicable and is optional. +type BlobInventoryPolicyFilter struct { + // An array of predefined enum values. Valid values include blockBlob, appendBlob, pageBlob. Hns accounts does not support + // pageBlobs. This field is required when definition.objectType property is set to + // 'Blob'. + BlobTypes []*string + + // This property is used to filter objects based on the object creation time + CreationTime *BlobInventoryCreationTime + + // An array of strings with maximum 10 blob prefixes to be excluded from the inventory. + ExcludePrefix []*string + + // Includes blob versions in blob inventory when value is set to true. The definition.schemaFields values 'VersionId and IsCurrentVersion' + // are required if this property is set to true, else they must be + // excluded. + IncludeBlobVersions *bool + + // For 'Container' definition.objectType the definition.schemaFields must include 'Deleted, Version, DeletedTime and RemainingRetentionDays'. + // For 'Blob' definition.objectType and HNS enabled storage + // accounts the definition.schemaFields must include 'DeletionId, Deleted, DeletedTime and RemainingRetentionDays' and for + // Hns disabled accounts the definition.schemaFields must include 'Deleted and + // RemainingRetentionDays', else it must be excluded. + IncludeDeleted *bool + + // Includes blob snapshots in blob inventory when value is set to true. The definition.schemaFields value 'Snapshot' is required + // if this property is set to true, else it must be excluded. + IncludeSnapshots *bool + + // An array of strings with maximum 10 blob prefixes to be included in the inventory. + PrefixMatch []*string +} + +// BlobInventoryPolicyProperties - The storage account blob inventory policy properties. +type BlobInventoryPolicyProperties struct { + // REQUIRED; The storage account blob inventory policy object. It is composed of policy rules. + Policy *BlobInventoryPolicySchema + + // READ-ONLY; Returns the last modified date and time of the blob inventory policy. + LastModifiedTime *time.Time +} + +// BlobInventoryPolicyRule - An object that wraps the blob inventory rule. Each rule is uniquely defined by name. +type BlobInventoryPolicyRule struct { + // REQUIRED; An object that defines the blob inventory policy rule. + Definition *BlobInventoryPolicyDefinition + + // REQUIRED; Container name where blob inventory files are stored. Must be pre-created. + Destination *string + + // REQUIRED; Rule is enabled when set to true. + Enabled *bool + + // REQUIRED; A rule name can contain any combination of alpha numeric characters. Rule name is case-sensitive. It must be + // unique within a policy. + Name *string +} + +// BlobInventoryPolicySchema - The storage account blob inventory policy rules. +type BlobInventoryPolicySchema struct { + // REQUIRED; Policy is enabled if set to true. + Enabled *bool + + // REQUIRED; The storage account blob inventory policy rules. The rule is applied when it is enabled. + Rules []*BlobInventoryPolicyRule + + // REQUIRED; The valid value is Inventory + Type *InventoryRuleType + + // READ-ONLY; Deprecated Property from API version 2021-04-01 onwards, the required destination container name must be specified + // at the rule level 'policy.rule.destination' + Destination *string +} + +// BlobRestoreParameters - Blob restore parameters +type BlobRestoreParameters struct { + // REQUIRED; Blob ranges to restore. + BlobRanges []*BlobRestoreRange + + // REQUIRED; Restore blob to the specified time. + TimeToRestore *time.Time +} + +// BlobRestoreRange - Blob range +type BlobRestoreRange struct { + // REQUIRED; Blob end range. This is exclusive. Empty means account end. + EndRange *string + + // REQUIRED; Blob start range. This is inclusive. Empty means account start. + StartRange *string +} + +// BlobRestoreStatus - Blob restore status. +type BlobRestoreStatus struct { + // READ-ONLY; Failure reason when blob restore is failed. + FailureReason *string + + // READ-ONLY; Blob restore request parameters. + Parameters *BlobRestoreParameters + + // READ-ONLY; Id for tracking blob restore request. + RestoreID *string + + // READ-ONLY; The status of blob restore progress. Possible values are: - InProgress: Indicates that blob restore is ongoing. + // - Complete: Indicates that blob restore has been completed successfully. - Failed: + // Indicates that blob restore is failed. + Status *BlobRestoreProgressStatus +} + +type BlobServiceItems struct { + // READ-ONLY; List of blob services returned. + Value []*BlobServiceProperties +} + +// BlobServiceProperties - The properties of a storage account’s Blob service. +type BlobServiceProperties struct { + // The properties of a storage account’s Blob service. + BlobServiceProperties *BlobServicePropertiesProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Sku name and tier. + SKU *SKU + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// BlobServicePropertiesProperties - The properties of a storage account’s Blob service. +type BlobServicePropertiesProperties struct { + // Deprecated in favor of isVersioningEnabled property. + AutomaticSnapshotPolicyEnabled *bool + + // The blob service properties for change feed events. + ChangeFeed *ChangeFeed + + // The blob service properties for container soft delete. + ContainerDeleteRetentionPolicy *DeleteRetentionPolicy + + // Specifies CORS rules for the Blob service. You can include up to five CorsRule elements in the request. If no CorsRule + // elements are included in the request body, all CORS rules will be deleted, and + // CORS will be disabled for the Blob service. + Cors *CorsRules + + // DefaultServiceVersion indicates the default version to use for requests to the Blob service if an incoming request’s version + // is not specified. Possible values include version 2008-10-27 and all more + // recent versions. + DefaultServiceVersion *string + + // The blob service properties for blob soft delete. + DeleteRetentionPolicy *DeleteRetentionPolicy + + // Versioning is enabled if set to true. + IsVersioningEnabled *bool + + // The blob service property to configure last access time based tracking policy. + LastAccessTimeTrackingPolicy *LastAccessTimeTrackingPolicy + + // The blob service properties for blob restore policy. + RestorePolicy *RestorePolicyProperties +} + +// ChangeFeed - The blob service properties for change feed events. +type ChangeFeed struct { + // Indicates whether change feed event logging is enabled for the Blob service. + Enabled *bool + + // Indicates the duration of changeFeed retention in days. Minimum value is 1 day and maximum value is 146000 days (400 years). + // A null value indicates an infinite retention of the change feed. + RetentionInDays *int32 +} + +// CheckNameAvailabilityResult - The CheckNameAvailability operation response. +type CheckNameAvailabilityResult struct { + // READ-ONLY; Gets an error message explaining the Reason value in more detail. + Message *string + + // READ-ONLY; Gets a boolean value that indicates whether the name is available for you to use. If true, the name is available. + // If false, the name has already been taken or is invalid and cannot be used. + NameAvailable *bool + + // READ-ONLY; Gets the reason that a storage account name could not be used. The Reason element is only returned if NameAvailable + // is false. + Reason *Reason +} + +// ContainerProperties - The properties of a container. +type ContainerProperties struct { + // Default the container to use specified encryption scope for all writes. + DefaultEncryptionScope *string + + // Block override of encryption scope from the container default. + DenyEncryptionScopeOverride *bool + + // Enable NFSv3 all squash on blob container. + EnableNfsV3AllSquash *bool + + // Enable NFSv3 root squash on blob container. + EnableNfsV3RootSquash *bool + + // The object level immutability property of the container. The property is immutable and can only be set to true at the container + // creation time. Existing containers must undergo a migration process. + ImmutableStorageWithVersioning *ImmutableStorageWithVersioning + + // A name-value pair to associate with the container as metadata. + Metadata map[string]*string + + // Specifies whether data in the container may be accessed publicly and the level of access. + PublicAccess *PublicAccess + + // READ-ONLY; Indicates whether the blob container was deleted. + Deleted *bool + + // READ-ONLY; Blob container deletion time. + DeletedTime *time.Time + + // READ-ONLY; The hasImmutabilityPolicy public property is set to true by SRP if ImmutabilityPolicy has been created for this + // container. The hasImmutabilityPolicy public property is set to false by SRP if + // ImmutabilityPolicy has not been created for this container. + HasImmutabilityPolicy *bool + + // READ-ONLY; The hasLegalHold public property is set to true by SRP if there are at least one existing tag. The hasLegalHold + // public property is set to false by SRP if all existing legal hold tags are cleared out. + // There can be a maximum of 1000 blob containers with hasLegalHold=true for a given account. + HasLegalHold *bool + + // READ-ONLY; The ImmutabilityPolicy property of the container. + ImmutabilityPolicy *ImmutabilityPolicyProperties + + // READ-ONLY; Returns the date and time the container was last modified. + LastModifiedTime *time.Time + + // READ-ONLY; Specifies whether the lease on a container is of infinite or fixed duration, only when the container is leased. + LeaseDuration *LeaseDuration + + // READ-ONLY; Lease state of the container. + LeaseState *LeaseState + + // READ-ONLY; The lease status of the container. + LeaseStatus *LeaseStatus + + // READ-ONLY; The LegalHold property of the container. + LegalHold *LegalHoldProperties + + // READ-ONLY; Remaining retention days for soft deleted blob container. + RemainingRetentionDays *int32 + + // READ-ONLY; The version of the deleted blob container. + Version *string +} + +// CorsRule - Specifies a CORS rule for the Blob service. +type CorsRule struct { + // REQUIRED; Required if CorsRule element is present. A list of headers allowed to be part of the cross-origin request. + AllowedHeaders []*string + + // REQUIRED; Required if CorsRule element is present. A list of HTTP methods that are allowed to be executed by the origin. + AllowedMethods []*CorsRuleAllowedMethodsItem + + // REQUIRED; Required if CorsRule element is present. A list of origin domains that will be allowed via CORS, or "*" to allow + // all domains + AllowedOrigins []*string + + // REQUIRED; Required if CorsRule element is present. A list of response headers to expose to CORS clients. + ExposedHeaders []*string + + // REQUIRED; Required if CorsRule element is present. The number of seconds that the client/browser should cache a preflight + // response. + MaxAgeInSeconds *int32 +} + +// CorsRules - Sets the CORS rules. You can include up to five CorsRule elements in the request. +type CorsRules struct { + // The List of CORS rules. You can include up to five CorsRule elements in the request. + CorsRules []*CorsRule +} + +// CustomDomain - The custom domain assigned to this storage account. This can be set via Update. +type CustomDomain struct { + // REQUIRED; Gets or sets the custom domain name assigned to the storage account. Name is the CNAME source. + Name *string + + // Indicates whether indirect CName validation is enabled. Default value is false. This should only be set on updates. + UseSubDomainName *bool +} + +// DateAfterCreation - Object to define snapshot and version action conditions. +type DateAfterCreation struct { + // REQUIRED; Value indicating the age in days after creation + DaysAfterCreationGreaterThan *float32 + + // Value indicating the age in days after last blob tier change time. This property is only applicable for tierToArchive actions + // and requires daysAfterCreationGreaterThan to be set for snapshots and blob + // version based actions. The blob will be archived if both the conditions are satisfied. + DaysAfterLastTierChangeGreaterThan *float32 +} + +// DateAfterModification - Object to define the base blob action conditions. Properties daysAfterModificationGreaterThan, +// daysAfterLastAccessTimeGreaterThan and daysAfterCreationGreaterThan are mutually exclusive. The +// daysAfterLastTierChangeGreaterThan property is only applicable for tierToArchive actions which requires daysAfterModificationGreaterThan +// to be set, also it cannot be used in conjunction with +// daysAfterLastAccessTimeGreaterThan or daysAfterCreationGreaterThan. +type DateAfterModification struct { + // Value indicating the age in days after blob creation. + DaysAfterCreationGreaterThan *float32 + + // Value indicating the age in days after last blob access. This property can only be used in conjunction with last access + // time tracking policy + DaysAfterLastAccessTimeGreaterThan *float32 + + // Value indicating the age in days after last blob tier change time. This property is only applicable for tierToArchive actions + // and requires daysAfterModificationGreaterThan to be set for baseBlobs + // based actions. The blob will be archived if both the conditions are satisfied. + DaysAfterLastTierChangeGreaterThan *float32 + + // Value indicating the age in days after last modification + DaysAfterModificationGreaterThan *float32 +} + +// DeleteRetentionPolicy - The service properties for soft delete. +type DeleteRetentionPolicy struct { + // This property when set to true allows deletion of the soft deleted blob versions and snapshots. This property cannot be + // used blob restore policy. This property only applies to blob service and does + // not apply to containers or file share. + AllowPermanentDelete *bool + + // Indicates the number of days that the deleted item should be retained. The minimum specified value can be 1 and the maximum + // value can be 365. + Days *int32 + + // Indicates whether DeleteRetentionPolicy is enabled. + Enabled *bool +} + +// DeletedAccount - Deleted storage account +type DeletedAccount struct { + // Properties of the deleted account. + Properties *DeletedAccountProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DeletedAccountListResult - The response from the List Deleted Accounts operation. +type DeletedAccountListResult struct { + // READ-ONLY; Request URL that can be used to query next page of deleted accounts. Returned when total number of requested + // deleted accounts exceed maximum page size. + NextLink *string + + // READ-ONLY; Gets the list of deleted accounts and their properties. + Value []*DeletedAccount +} + +// DeletedAccountProperties - Attributes of a deleted storage account. +type DeletedAccountProperties struct { + // READ-ONLY; Creation time of the deleted account. + CreationTime *string + + // READ-ONLY; Deletion time of the deleted account. + DeletionTime *string + + // READ-ONLY; Location of the deleted account. + Location *string + + // READ-ONLY; Can be used to attempt recovering this deleted account via PutStorageAccount API. + RestoreReference *string + + // READ-ONLY; Full resource id of the original storage account. + StorageAccountResourceID *string +} + +// DeletedShare - The deleted share to be restored. +type DeletedShare struct { + // REQUIRED; Required. Identify the name of the deleted share that will be restored. + DeletedShareName *string + + // REQUIRED; Required. Identify the version of the deleted share that will be restored. + DeletedShareVersion *string +} + +// Dimension of blobs, possibly be blob type or access tier. +type Dimension struct { + // Display name of dimension. + DisplayName *string + + // Display name of dimension. + Name *string +} + +// Encryption - The encryption settings on the storage account. +type Encryption struct { + // The identity to be used with service-side encryption at rest. + EncryptionIdentity *EncryptionIdentity + + // The encryption keySource (provider). Possible values (case-insensitive): Microsoft.Storage, Microsoft.Keyvault + KeySource *KeySource + + // Properties provided by key vault. + KeyVaultProperties *KeyVaultProperties + + // A boolean indicating whether or not the service applies a secondary layer of encryption with platform managed keys for + // data at rest. + RequireInfrastructureEncryption *bool + + // List of services which support encryption. + Services *EncryptionServices +} + +// EncryptionIdentity - Encryption identity for the storage account. +type EncryptionIdentity struct { + // ClientId of the multi-tenant application to be used in conjunction with the user-assigned identity for cross-tenant customer-managed-keys + // server-side encryption on the storage account. + EncryptionFederatedIdentityClientID *string + + // Resource identifier of the UserAssigned identity to be associated with server-side encryption on the storage account. + EncryptionUserAssignedIdentity *string +} + +// EncryptionScope - The Encryption Scope resource. +type EncryptionScope struct { + // Properties of the encryption scope. + EncryptionScopeProperties *EncryptionScopeProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// EncryptionScopeKeyVaultProperties - The key vault properties for the encryption scope. This is a required field if encryption +// scope 'source' attribute is set to 'Microsoft.KeyVault'. +type EncryptionScopeKeyVaultProperties struct { + // The object identifier for a key vault key object. When applied, the encryption scope will use the key referenced by the + // identifier to enable customer-managed key support on this encryption scope. + KeyURI *string + + // READ-ONLY; The object identifier of the current versioned Key Vault Key in use. + CurrentVersionedKeyIdentifier *string + + // READ-ONLY; Timestamp of last rotation of the Key Vault Key. + LastKeyRotationTimestamp *time.Time +} + +// EncryptionScopeListResult - List of encryption scopes requested, and if paging is required, a URL to the next page of encryption +// scopes. +type EncryptionScopeListResult struct { + // READ-ONLY; Request URL that can be used to query next page of encryption scopes. Returned when total number of requested + // encryption scopes exceeds the maximum page size. + NextLink *string + + // READ-ONLY; List of encryption scopes requested. + Value []*EncryptionScope +} + +// EncryptionScopeProperties - Properties of the encryption scope. +type EncryptionScopeProperties struct { + // The key vault properties for the encryption scope. This is a required field if encryption scope 'source' attribute is set + // to 'Microsoft.KeyVault'. + KeyVaultProperties *EncryptionScopeKeyVaultProperties + + // A boolean indicating whether or not the service applies a secondary layer of encryption with platform managed keys for + // data at rest. + RequireInfrastructureEncryption *bool + + // The provider for the encryption scope. Possible values (case-insensitive): Microsoft.Storage, Microsoft.KeyVault. + Source *EncryptionScopeSource + + // The state of the encryption scope. Possible values (case-insensitive): Enabled, Disabled. + State *EncryptionScopeState + + // READ-ONLY; Gets the creation date and time of the encryption scope in UTC. + CreationTime *time.Time + + // READ-ONLY; Gets the last modification date and time of the encryption scope in UTC. + LastModifiedTime *time.Time +} + +// EncryptionService - A service that allows server-side encryption to be used. +type EncryptionService struct { + // A boolean indicating whether or not the service encrypts the data as it is stored. Encryption at rest is enabled by default + // today and cannot be disabled. + Enabled *bool + + // Encryption key type to be used for the encryption service. 'Account' key type implies that an account-scoped encryption + // key will be used. 'Service' key type implies that a default service key is used. + KeyType *KeyType + + // READ-ONLY; Gets a rough estimate of the date/time when the encryption was last enabled by the user. Data is encrypted at + // rest by default today and cannot be disabled. + LastEnabledTime *time.Time +} + +// EncryptionServices - A list of services that support encryption. +type EncryptionServices struct { + // The encryption function of the blob storage service. + Blob *EncryptionService + + // The encryption function of the file storage service. + File *EncryptionService + + // The encryption function of the queue storage service. + Queue *EncryptionService + + // The encryption function of the table storage service. + Table *EncryptionService +} + +// Endpoints - The URIs that are used to perform a retrieval of a public blob, queue, table, web or dfs object. +type Endpoints struct { + // Gets the internet routing storage endpoints + InternetEndpoints *AccountInternetEndpoints + + // Gets the microsoft routing storage endpoints. + MicrosoftEndpoints *AccountMicrosoftEndpoints + + // READ-ONLY; Gets the blob endpoint. + Blob *string + + // READ-ONLY; Gets the dfs endpoint. + Dfs *string + + // READ-ONLY; Gets the file endpoint. + File *string + + // READ-ONLY; Gets the queue endpoint. + Queue *string + + // READ-ONLY; Gets the table endpoint. + Table *string + + // READ-ONLY; Gets the web endpoint. + Web *string +} + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info any + + // READ-ONLY; The additional info type. + Type *string +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo + + // READ-ONLY; The error code. + Code *string + + // READ-ONLY; The error details. + Details []*ErrorDetail + + // READ-ONLY; The error message. + Message *string + + // READ-ONLY; The error target. + Target *string +} + +// ErrorResponse - An error response from the storage resource provider. +type ErrorResponse struct { + // Azure Storage Resource Provider error response body. + Error *ErrorResponseBody +} + +// ErrorResponseAutoGenerated - Common error response for all Azure Resource Manager APIs to return error details for failed +// operations. (This also follows the OData error response format.). +type ErrorResponseAutoGenerated struct { + // The error object. + Error *ErrorDetail +} + +// ErrorResponseBody - Error response body contract. +type ErrorResponseBody struct { + // An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string + + // A message describing the error, intended to be suitable for display in a user interface. + Message *string +} + +// ExtendedLocation - The complex type of the extended location. +type ExtendedLocation struct { + // The name of the extended location. + Name *string + + // The type of the extended location. + Type *ExtendedLocationTypes +} + +type FileServiceItems struct { + // READ-ONLY; List of file services returned. + Value []*FileServiceProperties +} + +// FileServiceProperties - The properties of File services in storage account. +type FileServiceProperties struct { + // The properties of File services in storage account. + FileServiceProperties *FileServicePropertiesProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Sku name and tier. + SKU *SKU + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// FileServicePropertiesProperties - The properties of File services in storage account. +type FileServicePropertiesProperties struct { + // Specifies CORS rules for the File service. You can include up to five CorsRule elements in the request. If no CorsRule + // elements are included in the request body, all CORS rules will be deleted, and + // CORS will be disabled for the File service. + Cors *CorsRules + + // Protocol settings for file service + ProtocolSettings *ProtocolSettings + + // The file service properties for share soft delete. + ShareDeleteRetentionPolicy *DeleteRetentionPolicy +} + +// FileShare - Properties of the file share, including Id, resource name, resource type, Etag. +type FileShare struct { + // Properties of the file share. + FileShareProperties *FileShareProperties + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// FileShareItem - The file share properties be listed out. +type FileShareItem struct { + // The file share properties be listed out. + Properties *FileShareProperties + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// FileShareItems - Response schema. Contains list of shares returned, and if paging is requested or required, a URL to next +// page of shares. +type FileShareItems struct { + // READ-ONLY; Request URL that can be used to query next page of shares. Returned when total number of requested shares exceed + // maximum page size. + NextLink *string + + // READ-ONLY; List of file shares returned. + Value []*FileShareItem +} + +// FileShareProperties - The properties of the file share. +type FileShareProperties struct { + // Access tier for specific share. GpV2 account can choose between TransactionOptimized (default), Hot, and Cool. FileStorage + // account can choose Premium. + AccessTier *ShareAccessTier + + // The authentication protocol that is used for the file share. Can only be specified when creating a share. + EnabledProtocols *EnabledProtocols + + // A name-value pair to associate with the share as metadata. + Metadata map[string]*string + + // The property is for NFS share only. The default is NoRootSquash. + RootSquash *RootSquashType + + // The maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB (5120). For Large File + // Shares, the maximum size is 102400. + ShareQuota *int32 + + // List of stored access policies specified on the share. + SignedIdentifiers []*SignedIdentifier + + // READ-ONLY; Indicates the last modification time for share access tier. + AccessTierChangeTime *time.Time + + // READ-ONLY; Indicates if there is a pending transition for access tier. + AccessTierStatus *string + + // READ-ONLY; Indicates whether the share was deleted. + Deleted *bool + + // READ-ONLY; The deleted time if the share was deleted. + DeletedTime *time.Time + + // READ-ONLY; Returns the date and time the share was last modified. + LastModifiedTime *time.Time + + // READ-ONLY; Specifies whether the lease on a share is of infinite or fixed duration, only when the share is leased. + LeaseDuration *LeaseDuration + + // READ-ONLY; Lease state of the share. + LeaseState *LeaseState + + // READ-ONLY; The lease status of the share. + LeaseStatus *LeaseStatus + + // READ-ONLY; Remaining retention days for share that was soft deleted. + RemainingRetentionDays *int32 + + // READ-ONLY; The approximate size of the data stored on the share. Note that this value may not include all recently created + // or recently resized files. + ShareUsageBytes *int64 + + // READ-ONLY; Creation time of share snapshot returned in the response of list shares with expand param "snapshots". + SnapshotTime *time.Time + + // READ-ONLY; The version of the share. + Version *string +} + +// GeoReplicationStats - Statistics related to replication for storage account's Blob, Table, Queue and File services. It +// is only available when geo-redundant replication is enabled for the storage account. +type GeoReplicationStats struct { + // READ-ONLY; A boolean flag which indicates whether or not account failover is supported for the account. + CanFailover *bool + + // READ-ONLY; A boolean flag which indicates whether or not planned account failover is supported for the account. + CanPlannedFailover *bool + + // READ-ONLY; All primary writes preceding this UTC date/time value are guaranteed to be available for read operations. Primary + // writes following this point in time may or may not be available for reads. Element may + // be default value if value of LastSyncTime is not available, this can happen if secondary is offline or we are in bootstrap. + LastSyncTime *time.Time + + // READ-ONLY; The redundancy type of the account after an account failover is performed. + PostFailoverRedundancy *PostFailoverRedundancy + + // READ-ONLY; The redundancy type of the account after a planned account failover is performed. + PostPlannedFailoverRedundancy *PostPlannedFailoverRedundancy + + // READ-ONLY; The status of the secondary location. Possible values are: - Live: Indicates that the secondary location is + // active and operational. - Bootstrap: Indicates initial synchronization from the primary + // location to the secondary location is in progress.This typically occurs when replication is first enabled. - Unavailable: + // Indicates that the secondary location is temporarily unavailable. + Status *GeoReplicationStatus +} + +// IPRule - IP rule with specific IP or IP range in CIDR format. +type IPRule struct { + // REQUIRED; Specifies the IP or IP range in CIDR format. Only IPV4 address is allowed. + IPAddressOrRange *string + + // The action of IP ACL rule. + Action *string +} + +// Identity for the resource. +type Identity struct { + // REQUIRED; The identity type. + Type *IdentityType + + // Gets or sets a list of key value pairs that describe the set of User Assigned identities that will be used with this storage + // account. The key is the ARM resource identifier of the identity. Only 1 + // User Assigned identity is permitted here. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The principal ID of resource identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of resource. + TenantID *string +} + +// ImmutabilityPolicy - The ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. +type ImmutabilityPolicy struct { + // REQUIRED; The properties of an ImmutabilityPolicy of a blob container. + Properties *ImmutabilityPolicyProperty + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ImmutabilityPolicyProperties - The properties of an ImmutabilityPolicy of a blob container. +type ImmutabilityPolicyProperties struct { + // The properties of an ImmutabilityPolicy of a blob container. + Properties *ImmutabilityPolicyProperty + + // READ-ONLY; ImmutabilityPolicy Etag. + Etag *string + + // READ-ONLY; The ImmutabilityPolicy update history of the blob container. + UpdateHistory []*UpdateHistoryProperty +} + +// ImmutabilityPolicyProperty - The properties of an ImmutabilityPolicy of a blob container. +type ImmutabilityPolicyProperty struct { + // This property can only be changed for unlocked time-based retention policies. When enabled, new blocks can be written to + // an append blob while maintaining immutability protection and compliance. Only + // new blocks can be added and any existing blocks cannot be modified or deleted. This property cannot be changed with ExtendImmutabilityPolicy + // API. + AllowProtectedAppendWrites *bool + + // This property can only be changed for unlocked time-based retention policies. When enabled, new blocks can be written to + // both 'Append and Bock Blobs' while maintaining immutability protection and + // compliance. Only new blocks can be added and any existing blocks cannot be modified or deleted. This property cannot be + // changed with ExtendImmutabilityPolicy API. The 'allowProtectedAppendWrites' and + // 'allowProtectedAppendWritesAll' properties are mutually exclusive. + AllowProtectedAppendWritesAll *bool + + // The immutability period for the blobs in the container since the policy creation, in days. + ImmutabilityPeriodSinceCreationInDays *int32 + + // READ-ONLY; The ImmutabilityPolicy state of a blob container, possible values include: Locked and Unlocked. + State *ImmutabilityPolicyState +} + +// ImmutableStorageAccount - This property enables and defines account-level immutability. Enabling the feature auto-enables +// Blob Versioning. +type ImmutableStorageAccount struct { + // A boolean flag which enables account-level immutability. All the containers under such an account have object-level immutability + // enabled by default. + Enabled *bool + + // Specifies the default account-level immutability policy which is inherited and applied to objects that do not possess an + // explicit immutability policy at the object level. The object-level immutability + // policy has higher precedence than the container-level immutability policy, which has a higher precedence than the account-level + // immutability policy. + ImmutabilityPolicy *AccountImmutabilityPolicyProperties +} + +// ImmutableStorageWithVersioning - Object level immutability properties of the container. +type ImmutableStorageWithVersioning struct { + // This is an immutable property, when set to true it enables object level immutability at the container level. + Enabled *bool + + // READ-ONLY; This property denotes the container level immutability to object level immutability migration state. + MigrationState *MigrationState + + // READ-ONLY; Returns the date and time the object level immutability was enabled. + TimeStamp *time.Time +} + +// KeyCreationTime - Storage account keys creation time. +type KeyCreationTime struct { + Key1 *time.Time + Key2 *time.Time +} + +// KeyPolicy assigned to the storage account. +type KeyPolicy struct { + // REQUIRED; The key expiration period in days. + KeyExpirationPeriodInDays *int32 +} + +// KeyVaultProperties - Properties of key vault. +type KeyVaultProperties struct { + // The name of KeyVault key. + KeyName *string + + // The Uri of KeyVault. + KeyVaultURI *string + + // The version of KeyVault key. + KeyVersion *string + + // READ-ONLY; This is a read only property that represents the expiration time of the current version of the customer managed + // key used for encryption. + CurrentVersionedKeyExpirationTimestamp *time.Time + + // READ-ONLY; The object identifier of the current versioned Key Vault Key in use. + CurrentVersionedKeyIdentifier *string + + // READ-ONLY; Timestamp of last rotation of the Key Vault Key. + LastKeyRotationTimestamp *time.Time +} + +// LastAccessTimeTrackingPolicy - The blob service properties for Last access time based tracking policy. +type LastAccessTimeTrackingPolicy struct { + // REQUIRED; When set to true last access time based tracking is enabled. + Enable *bool + + // An array of predefined supported blob types. Only blockBlob is the supported value. This field is currently read only + BlobType []*string + + // Name of the policy. The valid value is AccessTimeTracking. This field is currently read only + Name *Name + + // The field specifies blob object tracking granularity in days, typically how often the blob object should be tracked.This + // field is currently read only with value as 1 + TrackingGranularityInDays *int32 +} + +// LeaseContainerRequest - Lease Container request schema. +type LeaseContainerRequest struct { + // REQUIRED; Specifies the lease action. Can be one of the available actions. + Action *LeaseContainerRequestAction + + // Optional. For a break action, proposed duration the lease should continue before it is broken, in seconds, between 0 and + // 60. + BreakPeriod *int32 + + // Required for acquire. Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. + LeaseDuration *int32 + + // Identifies the lease. Can be specified in any valid GUID string format. + LeaseID *string + + // Optional for acquire, required for change. Proposed lease ID, in a GUID string format. + ProposedLeaseID *string +} + +// LeaseContainerResponse - Lease Container response schema. +type LeaseContainerResponse struct { + // Returned unique lease ID that must be included with any request to delete the container, or to renew, change, or release + // the lease. + LeaseID *string + + // Approximate time remaining in the lease period, in seconds. + LeaseTimeSeconds *string +} + +// LeaseShareRequest - Lease Share request schema. +type LeaseShareRequest struct { + // REQUIRED; Specifies the lease action. Can be one of the available actions. + Action *LeaseShareAction + + // Optional. For a break action, proposed duration the lease should continue before it is broken, in seconds, between 0 and + // 60. + BreakPeriod *int32 + + // Required for acquire. Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. + LeaseDuration *int32 + + // Identifies the lease. Can be specified in any valid GUID string format. + LeaseID *string + + // Optional for acquire, required for change. Proposed lease ID, in a GUID string format. + ProposedLeaseID *string +} + +// LeaseShareResponse - Lease Share response schema. +type LeaseShareResponse struct { + // Returned unique lease ID that must be included with any request to delete the share, or to renew, change, or release the + // lease. + LeaseID *string + + // Approximate time remaining in the lease period, in seconds. + LeaseTimeSeconds *string +} + +// LegalHold - The LegalHold property of a blob container. +type LegalHold struct { + // REQUIRED; Each tag should be 3 to 23 alphanumeric characters and is normalized to lower case at SRP. + Tags []*string + + // When enabled, new blocks can be written to both 'Append and Bock Blobs' while maintaining legal hold protection and compliance. + // Only new blocks can be added and any existing blocks cannot be modified + // or deleted. + AllowProtectedAppendWritesAll *bool + + // READ-ONLY; The hasLegalHold public property is set to true by SRP if there are at least one existing tag. The hasLegalHold + // public property is set to false by SRP if all existing legal hold tags are cleared out. + // There can be a maximum of 1000 blob containers with hasLegalHold=true for a given account. + HasLegalHold *bool +} + +// LegalHoldProperties - The LegalHold property of a blob container. +type LegalHoldProperties struct { + // Protected append blob writes history. + ProtectedAppendWritesHistory *ProtectedAppendWritesHistory + + // The list of LegalHold tags of a blob container. + Tags []*TagProperty + + // READ-ONLY; The hasLegalHold public property is set to true by SRP if there are at least one existing tag. The hasLegalHold + // public property is set to false by SRP if all existing legal hold tags are cleared out. + // There can be a maximum of 1000 blob containers with hasLegalHold=true for a given account. + HasLegalHold *bool +} + +// ListAccountSasResponse - The List SAS credentials operation response. +type ListAccountSasResponse struct { + // READ-ONLY; List SAS credentials of storage account. + AccountSasToken *string +} + +// ListBlobInventoryPolicy - List of blob inventory policies returned. +type ListBlobInventoryPolicy struct { + // READ-ONLY; List of blob inventory policies. + Value []*BlobInventoryPolicy +} + +// ListContainerItem - The blob container properties be listed out. +type ListContainerItem struct { + // The blob container properties be listed out. + Properties *ContainerProperties + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ListContainerItems - Response schema. Contains list of blobs returned, and if paging is requested or required, a URL to +// next page of containers. +type ListContainerItems struct { + // READ-ONLY; Request URL that can be used to query next page of containers. Returned when total number of requested containers + // exceed maximum page size. + NextLink *string + + // READ-ONLY; List of blobs containers returned. + Value []*ListContainerItem +} + +type ListQueue struct { + // List Queue resource properties. + QueueProperties *ListQueueProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type ListQueueProperties struct { + // A name-value pair that represents queue metadata. + Metadata map[string]*string +} + +// ListQueueResource - Response schema. Contains list of queues returned +type ListQueueResource struct { + // READ-ONLY; Request URL that can be used to list next page of queues + NextLink *string + + // READ-ONLY; List of queues returned. + Value []*ListQueue +} + +type ListQueueServices struct { + // READ-ONLY; List of queue services returned. + Value []*QueueServiceProperties +} + +// ListServiceSasResponse - The List service SAS credentials operation response. +type ListServiceSasResponse struct { + // READ-ONLY; List service SAS credentials of specific resource. + ServiceSasToken *string +} + +// ListTableResource - Response schema. Contains list of tables returned +type ListTableResource struct { + // READ-ONLY; Request URL that can be used to query next page of tables + NextLink *string + + // READ-ONLY; List of tables returned. + Value []*Table +} + +type ListTableServices struct { + // READ-ONLY; List of table services returned. + Value []*TableServiceProperties +} + +// LocalUser - The local user associated with the storage accounts. +type LocalUser struct { + // Storage account local user properties. + Properties *LocalUserProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// LocalUserKeys - The Storage Account Local User keys. +type LocalUserKeys struct { + // Optional, local user ssh authorized keys for SFTP. + SSHAuthorizedKeys []*SSHPublicKey + + // READ-ONLY; Auto generated by the server for SMB authentication. + SharedKey *string +} + +// LocalUserProperties - The Storage Account Local User properties. +type LocalUserProperties struct { + // Indicates whether ssh key exists. Set it to false to remove existing SSH key. + HasSSHKey *bool + + // Indicates whether ssh password exists. Set it to false to remove existing SSH password. + HasSSHPassword *bool + + // Indicates whether shared key exists. Set it to false to remove existing shared key. + HasSharedKey *bool + + // Optional, local user home directory. + HomeDirectory *string + + // The permission scopes of the local user. + PermissionScopes []*PermissionScope + + // Optional, local user ssh authorized keys for SFTP. + SSHAuthorizedKeys []*SSHPublicKey + + // READ-ONLY; A unique Security Identifier that is generated by the server. + Sid *string +} + +// LocalUserRegeneratePasswordResult - The secrets of Storage Account Local User. +type LocalUserRegeneratePasswordResult struct { + // READ-ONLY; Auto generated password by the server for SSH authentication if hasSshPassword is set to true on the creation + // of local user. + SSHPassword *string +} + +// LocalUsers - List storage account local users. +type LocalUsers struct { + // The local users associated with the storage account. + Value []*LocalUser +} + +// ManagementPolicy - The Get Storage Account ManagementPolicies operation response. +type ManagementPolicy struct { + // Returns the Storage Account Data Policies Rules. + Properties *ManagementPolicyProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ManagementPolicyAction - Actions are applied to the filtered blobs when the execution condition is met. +type ManagementPolicyAction struct { + // The management policy action for base blob + BaseBlob *ManagementPolicyBaseBlob + + // The management policy action for snapshot + Snapshot *ManagementPolicySnapShot + + // The management policy action for version + Version *ManagementPolicyVersion +} + +// ManagementPolicyBaseBlob - Management policy action for base blob. +type ManagementPolicyBaseBlob struct { + // The function to delete the blob + Delete *DateAfterModification + + // This property enables auto tiering of a blob from cool to hot on a blob access. This property requires tierToCool.daysAfterLastAccessTimeGreaterThan. + EnableAutoTierToHotFromCool *bool + + // The function to tier blobs to archive storage. + TierToArchive *DateAfterModification + + // The function to tier blobs to cold storage. + TierToCold *DateAfterModification + + // The function to tier blobs to cool storage. + TierToCool *DateAfterModification + + // The function to tier blobs to hot storage. This action can only be used with Premium Block Blob Storage Accounts + TierToHot *DateAfterModification +} + +// ManagementPolicyDefinition - An object that defines the Lifecycle rule. Each definition is made up with a filters set and +// an actions set. +type ManagementPolicyDefinition struct { + // REQUIRED; An object that defines the action set. + Actions *ManagementPolicyAction + + // An object that defines the filter set. + Filters *ManagementPolicyFilter +} + +// ManagementPolicyFilter - Filters limit rule actions to a subset of blobs within the storage account. If multiple filters +// are defined, a logical AND is performed on all filters. +type ManagementPolicyFilter struct { + // REQUIRED; An array of predefined enum values. Currently blockBlob supports all tiering and delete actions. Only delete + // actions are supported for appendBlob. + BlobTypes []*string + + // An array of blob index tag based filters, there can be at most 10 tag filters + BlobIndexMatch []*TagFilter + + // An array of strings for prefixes to be match. + PrefixMatch []*string +} + +// ManagementPolicyProperties - The Storage Account ManagementPolicy properties. +type ManagementPolicyProperties struct { + // REQUIRED; The Storage Account ManagementPolicy, in JSON format. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts. + Policy *ManagementPolicySchema + + // READ-ONLY; Returns the date and time the ManagementPolicies was last modified. + LastModifiedTime *time.Time +} + +// ManagementPolicyRule - An object that wraps the Lifecycle rule. Each rule is uniquely defined by name. +type ManagementPolicyRule struct { + // REQUIRED; An object that defines the Lifecycle rule. + Definition *ManagementPolicyDefinition + + // REQUIRED; A rule name can contain any combination of alpha numeric characters. Rule name is case-sensitive. It must be + // unique within a policy. + Name *string + + // REQUIRED; The valid value is Lifecycle + Type *RuleType + + // Rule is enabled if set to true. + Enabled *bool +} + +// ManagementPolicySchema - The Storage Account ManagementPolicies Rules. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts. +type ManagementPolicySchema struct { + // REQUIRED; The Storage Account ManagementPolicies Rules. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts. + Rules []*ManagementPolicyRule +} + +// ManagementPolicySnapShot - Management policy action for snapshot. +type ManagementPolicySnapShot struct { + // The function to delete the blob snapshot + Delete *DateAfterCreation + + // The function to tier blob snapshot to archive storage. + TierToArchive *DateAfterCreation + + // The function to tier blobs to cold storage. + TierToCold *DateAfterCreation + + // The function to tier blob snapshot to cool storage. + TierToCool *DateAfterCreation + + // The function to tier blobs to hot storage. This action can only be used with Premium Block Blob Storage Accounts + TierToHot *DateAfterCreation +} + +// ManagementPolicyVersion - Management policy action for blob version. +type ManagementPolicyVersion struct { + // The function to delete the blob version + Delete *DateAfterCreation + + // The function to tier blob version to archive storage. + TierToArchive *DateAfterCreation + + // The function to tier blobs to cold storage. + TierToCold *DateAfterCreation + + // The function to tier blob version to cool storage. + TierToCool *DateAfterCreation + + // The function to tier blobs to hot storage. This action can only be used with Premium Block Blob Storage Accounts + TierToHot *DateAfterCreation +} + +// MetricSpecification - Metric specification of operation. +type MetricSpecification struct { + // Aggregation type could be Average. + AggregationType *string + + // The category this metric specification belong to, could be Capacity. + Category *string + + // Dimensions of blobs, including blob type and access tier. + Dimensions []*Dimension + + // Display description of metric specification. + DisplayDescription *string + + // Display name of metric specification. + DisplayName *string + + // The property to decide fill gap with zero or not. + FillGapWithZero *bool + + // Name of metric specification. + Name *string + + // Account Resource Id. + ResourceIDDimensionNameOverride *string + + // Unit could be Bytes or Count. + Unit *string +} + +// Multichannel setting. Applies to Premium FileStorage only. +type Multichannel struct { + // Indicates whether multichannel is enabled + Enabled *bool +} + +// NetworkRuleSet - Network rule set +type NetworkRuleSet struct { + // REQUIRED; Specifies the default action of allow or deny when no other rules match. + DefaultAction *DefaultAction + + // Specifies whether traffic is bypassed for Logging/Metrics/AzureServices. Possible values are any combination of Logging|Metrics|AzureServices + // (For example, "Logging, Metrics"), or None to bypass none + // of those traffics. + Bypass *Bypass + + // Sets the IP ACL rules + IPRules []*IPRule + + // Sets the resource access rules + ResourceAccessRules []*ResourceAccessRule + + // Sets the virtual network rules + VirtualNetworkRules []*VirtualNetworkRule +} + +// ObjectReplicationPolicies - List storage account object replication policies. +type ObjectReplicationPolicies struct { + // The replication policy between two storage accounts. + Value []*ObjectReplicationPolicy +} + +// ObjectReplicationPolicy - The replication policy between two storage accounts. Multiple rules can be defined in one policy. +type ObjectReplicationPolicy struct { + // Returns the Storage Account Object Replication Policy. + Properties *ObjectReplicationPolicyProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ObjectReplicationPolicyFilter - Filters limit replication to a subset of blobs within the storage account. A logical OR +// is performed on values in the filter. If multiple filters are defined, a logical AND is performed on all +// filters. +type ObjectReplicationPolicyFilter struct { + // Blobs created after the time will be replicated to the destination. It must be in datetime format 'yyyy-MM-ddTHH:mm:ssZ'. + // Example: 2020-02-19T16:05:00Z + MinCreationTime *string + + // Optional. Filters the results to replicate only blobs whose names begin with the specified prefix. + PrefixMatch []*string +} + +// ObjectReplicationPolicyProperties - The Storage Account ObjectReplicationPolicy properties. +type ObjectReplicationPolicyProperties struct { + // REQUIRED; Required. Destination account name. It should be full resource id if allowCrossTenantReplication set to false. + DestinationAccount *string + + // REQUIRED; Required. Source account name. It should be full resource id if allowCrossTenantReplication set to false. + SourceAccount *string + + // The storage account object replication rules. + Rules []*ObjectReplicationPolicyRule + + // READ-ONLY; Indicates when the policy is enabled on the source account. + EnabledTime *time.Time + + // READ-ONLY; A unique id for object replication policy. + PolicyID *string +} + +// ObjectReplicationPolicyRule - The replication policy rule between two containers. +type ObjectReplicationPolicyRule struct { + // REQUIRED; Required. Destination container name. + DestinationContainer *string + + // REQUIRED; Required. Source container name. + SourceContainer *string + + // Optional. An object that defines the filter set. + Filters *ObjectReplicationPolicyFilter + + // Rule Id is auto-generated for each new rule on destination account. It is required for put policy on source account. + RuleID *string +} + +// Operation - Storage REST API operation definition. +type Operation struct { + // Display metadata associated with the operation. + Display *OperationDisplay + + // Operation name: {provider}/{resource}/{operation} + Name *string + + // Properties of operation, include metric specifications. + OperationProperties *OperationProperties + + // The origin of operations. + Origin *string +} + +// OperationDisplay - Display metadata associated with the operation. +type OperationDisplay struct { + // Description of the operation. + Description *string + + // Type of operation: get, read, delete, etc. + Operation *string + + // Service provider: Microsoft Storage. + Provider *string + + // Resource on which the operation is performed etc. + Resource *string +} + +// OperationListResult - Result of the request to list Storage operations. It contains a list of operations and a URL link +// to get the next set of results. +type OperationListResult struct { + // List of Storage operations supported by the Storage resource provider. + Value []*Operation +} + +// OperationProperties - Properties of operation, include metric specifications. +type OperationProperties struct { + // One property of operation, include metric specifications. + ServiceSpecification *ServiceSpecification +} + +type PermissionScope struct { + // REQUIRED; The permissions for the local user. Possible values include: Read (r), Write (w), Delete (d), List (l), and Create + // (c). + Permissions *string + + // REQUIRED; The name of resource, normally the container name or the file share name, used by the local user. + ResourceName *string + + // REQUIRED; The service used by the local user, e.g. blob, file. + Service *string +} + +// PrivateEndpoint - The Private Endpoint resource. +type PrivateEndpoint struct { + // READ-ONLY; The ARM identifier for Private Endpoint + ID *string +} + +// PrivateEndpointConnection - The Private Endpoint Connection resource. +type PrivateEndpointConnection struct { + // Resource properties. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateEndpointConnectionListResult - List of private endpoint connection associated with the specified storage account +type PrivateEndpointConnectionListResult struct { + // Array of private endpoint connections + Value []*PrivateEndpointConnection +} + +// PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnectProperties. +type PrivateEndpointConnectionProperties struct { + // REQUIRED; A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // The resource of private end point. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *PrivateEndpointConnectionProvisioningState +} + +// PrivateLinkResource - A private link resource +type PrivateLinkResource struct { + // Resource properties. + Properties *PrivateLinkResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateLinkResourceListResult - A list of private link resources +type PrivateLinkResourceListResult struct { + // Array of private link resources + Value []*PrivateLinkResource +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource Private link DNS zone name. + RequiredZoneNames []*string + + // READ-ONLY; The private link resource group id. + GroupID *string + + // READ-ONLY; The private link resource required member names. + RequiredMembers []*string +} + +// PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer +// and provider. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionRequired *string + + // The reason for approval/rejection of the connection. + Description *string + + // Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + Status *PrivateEndpointServiceConnectionStatus +} + +// ProtectedAppendWritesHistory - Protected append writes history setting for the blob container with Legal holds. +type ProtectedAppendWritesHistory struct { + // When enabled, new blocks can be written to both 'Append and Bock Blobs' while maintaining legal hold protection and compliance. + // Only new blocks can be added and any existing blocks cannot be modified + // or deleted. + AllowProtectedAppendWritesAll *bool + + // READ-ONLY; Returns the date and time the tag was added. + Timestamp *time.Time +} + +// ProtocolSettings - Protocol settings for file service +type ProtocolSettings struct { + // Setting for SMB protocol + Smb *SmbSetting +} + +// ProxyResource - The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a +// location +type ProxyResource struct { + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type Queue struct { + // Queue resource properties. + QueueProperties *QueueProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type QueueProperties struct { + // A name-value pair that represents queue metadata. + Metadata map[string]*string + + // READ-ONLY; Integer indicating an approximate number of messages in the queue. This number is not lower than the actual + // number of messages in the queue, but could be higher. + ApproximateMessageCount *int32 +} + +// QueueServiceProperties - The properties of a storage account’s Queue service. +type QueueServiceProperties struct { + // The properties of a storage account’s Queue service. + QueueServiceProperties *QueueServicePropertiesProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// QueueServicePropertiesProperties - The properties of a storage account’s Queue service. +type QueueServicePropertiesProperties struct { + // Specifies CORS rules for the Queue service. You can include up to five CorsRule elements in the request. If no CorsRule + // elements are included in the request body, all CORS rules will be deleted, and + // CORS will be disabled for the Queue service. + Cors *CorsRules +} + +// Resource - Common fields that are returned in the response for all Azure Resource Manager resources +type Resource struct { + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ResourceAccessRule - Resource Access Rule. +type ResourceAccessRule struct { + // Resource Id + ResourceID *string + + // Tenant Id + TenantID *string +} + +// RestorePolicyProperties - The blob service properties for blob restore policy +type RestorePolicyProperties struct { + // REQUIRED; Blob restore is enabled if set to true. + Enabled *bool + + // how long this blob can be restored. It should be great than zero and less than DeleteRetentionPolicy.days. + Days *int32 + + // READ-ONLY; Deprecated in favor of minRestoreTime property. + LastEnabledTime *time.Time + + // READ-ONLY; Returns the minimum date and time that the restore can be started. + MinRestoreTime *time.Time +} + +// Restriction - The restriction because of which SKU cannot be used. +type Restriction struct { + // The reason for the restriction. As of now this can be "QuotaId" or "NotAvailableForSubscription". Quota Id is set when + // the SKU has requiredQuotas parameter as the subscription does not belong to that + // quota. The "NotAvailableForSubscription" is related to capacity at DC. + ReasonCode *ReasonCode + + // READ-ONLY; The type of restrictions. As of now only possible value for this is location. + Type *string + + // READ-ONLY; The value of restrictions. If the restriction type is set to location. This would be different locations where + // the SKU is restricted. + Values []*string +} + +// RoutingPreference - Routing preference defines the type of network, either microsoft or internet routing to be used to +// deliver the user data, the default option is microsoft routing +type RoutingPreference struct { + // A boolean flag which indicates whether internet routing storage endpoints are to be published + PublishInternetEndpoints *bool + + // A boolean flag which indicates whether microsoft routing storage endpoints are to be published + PublishMicrosoftEndpoints *bool + + // Routing Choice defines the kind of network routing opted by the user. + RoutingChoice *RoutingChoice +} + +// SKU - The SKU of the storage account. +type SKU struct { + // REQUIRED; The SKU name. Required for account creation; optional for update. Note that in older versions, SKU name was called + // accountType. + Name *SKUName + + // READ-ONLY; The SKU tier. This is based on the SKU name. + Tier *SKUTier +} + +// SKUCapability - The capability information in the specified SKU, including file encryption, network ACLs, change notification, +// etc. +type SKUCapability struct { + // READ-ONLY; The name of capability, The capability information in the specified SKU, including file encryption, network + // ACLs, change notification, etc. + Name *string + + // READ-ONLY; A string value to indicate states of given capability. Possibly 'true' or 'false'. + Value *string +} + +// SKUInformation - Storage SKU and its properties +type SKUInformation struct { + // REQUIRED; The SKU name. Required for account creation; optional for update. Note that in older versions, SKU name was called + // accountType. + Name *SKUName + + // The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. + Restrictions []*Restriction + + // READ-ONLY; The capability information in the specified SKU, including file encryption, network ACLs, change notification, + // etc. + Capabilities []*SKUCapability + + // READ-ONLY; Indicates the type of storage account. + Kind *Kind + + // READ-ONLY; The set of locations that the SKU is available. This will be supported and registered Azure Geo Regions (e.g. + // West US, East US, Southeast Asia, etc.). + Locations []*string + + // READ-ONLY; The type of the resource, usually it is 'storageAccounts'. + ResourceType *string + + // READ-ONLY; The SKU tier. This is based on the SKU name. + Tier *SKUTier +} + +// SKUListResult - The response from the List Storage SKUs operation. +type SKUListResult struct { + // READ-ONLY; Get the list result of storage SKUs and their properties. + Value []*SKUInformation +} + +type SSHPublicKey struct { + // Optional. It is used to store the function/usage of the key + Description *string + + // Ssh public key base64 encoded. The format should be: ' ', e.g. ssh-rsa AAAABBBB + Key *string +} + +// SasPolicy assigned to the storage account. +type SasPolicy struct { + // REQUIRED; The SAS expiration action. Can only be Log. + ExpirationAction *ExpirationAction + + // REQUIRED; The SAS expiration period, DD.HH:MM:SS. + SasExpirationPeriod *string +} + +// ServiceSasParameters - The parameters to list service SAS credentials of a specific resource. +type ServiceSasParameters struct { + // REQUIRED; The canonical path to the signed resource. + CanonicalizedResource *string + + // The response header override for cache control. + CacheControl *string + + // The response header override for content disposition. + ContentDisposition *string + + // The response header override for content encoding. + ContentEncoding *string + + // The response header override for content language. + ContentLanguage *string + + // The response header override for content type. + ContentType *string + + // An IP address or a range of IP addresses from which to accept requests. + IPAddressOrRange *string + + // A unique value up to 64 characters in length that correlates to an access policy specified for the container, queue, or + // table. + Identifier *string + + // The key to sign the account SAS token with. + KeyToSign *string + + // The end of partition key. + PartitionKeyEnd *string + + // The start of partition key. + PartitionKeyStart *string + + // The signed permissions for the service SAS. Possible values include: Read (r), Write (w), Delete (d), List (l), Add (a), + // Create (c), Update (u) and Process (p). + Permissions *Permissions + + // The protocol permitted for a request made with the account SAS. + Protocols *HTTPProtocol + + // The signed services accessible with the service SAS. Possible values include: Blob (b), Container (c), File (f), Share + // (s). + Resource *SignedResource + + // The end of row key. + RowKeyEnd *string + + // The start of row key. + RowKeyStart *string + + // The time at which the shared access signature becomes invalid. + SharedAccessExpiryTime *time.Time + + // The time at which the SAS becomes valid. + SharedAccessStartTime *time.Time +} + +// ServiceSpecification - One property of operation, include metric specifications. +type ServiceSpecification struct { + // Metric specifications of operation. + MetricSpecifications []*MetricSpecification +} + +type SignedIdentifier struct { + // Access policy + AccessPolicy *AccessPolicy + + // An unique identifier of the stored access policy. + ID *string +} + +// SmbSetting - Setting for SMB protocol +type SmbSetting struct { + // SMB authentication methods supported by server. Valid values are NTLMv2, Kerberos. Should be passed as a string with delimiter + // ';'. + AuthenticationMethods *string + + // SMB channel encryption supported by server. Valid values are AES-128-CCM, AES-128-GCM, AES-256-GCM. Should be passed as + // a string with delimiter ';'. + ChannelEncryption *string + + // Kerberos ticket encryption supported by server. Valid values are RC4-HMAC, AES-256. Should be passed as a string with delimiter + // ';' + KerberosTicketEncryption *string + + // Multichannel setting. Applies to Premium FileStorage only. + Multichannel *Multichannel + + // SMB protocol versions supported by server. Valid values are SMB2.1, SMB3.0, SMB3.1.1. Should be passed as a string with + // delimiter ';'. + Versions *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// Table - Properties of the table, including Id, resource name, resource type. +type Table struct { + // Table resource properties. + TableProperties *TableProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// TableAccessPolicy - Table Access Policy Properties Object. +type TableAccessPolicy struct { + // REQUIRED; Required. List of abbreviated permissions. Supported permission values include 'r','a','u','d' + Permission *string + + // Expiry time of the access policy + ExpiryTime *time.Time + + // Start time of the access policy + StartTime *time.Time +} + +type TableProperties struct { + // List of stored access policies specified on the table. + SignedIdentifiers []*TableSignedIdentifier + + // READ-ONLY; Table name under the specified account + TableName *string +} + +// TableServiceProperties - The properties of a storage account’s Table service. +type TableServiceProperties struct { + // The properties of a storage account’s Table service. + TableServiceProperties *TableServicePropertiesProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// TableServicePropertiesProperties - The properties of a storage account’s Table service. +type TableServicePropertiesProperties struct { + // Specifies CORS rules for the Table service. You can include up to five CorsRule elements in the request. If no CorsRule + // elements are included in the request body, all CORS rules will be deleted, and + // CORS will be disabled for the Table service. + Cors *CorsRules +} + +// TableSignedIdentifier - Object to set Table Access Policy. +type TableSignedIdentifier struct { + // REQUIRED; unique-64-character-value of the stored access policy. + ID *string + + // Access policy + AccessPolicy *TableAccessPolicy +} + +// TagFilter - Blob index tag based filtering for blob objects +type TagFilter struct { + // REQUIRED; This is the filter tag name, it can have 1 - 128 characters + Name *string + + // REQUIRED; This is the comparison operator which is used for object comparison and filtering. Only == (equality operator) + // is currently supported + Op *string + + // REQUIRED; This is the filter tag value field used for tag based filtering, it can have 0 - 256 characters + Value *string +} + +// TagProperty - A tag of the LegalHold of a blob container. +type TagProperty struct { + // READ-ONLY; Returns the Object ID of the user who added the tag. + ObjectIdentifier *string + + // READ-ONLY; The tag value. + Tag *string + + // READ-ONLY; Returns the Tenant ID that issued the token for the user who added the tag. + TenantID *string + + // READ-ONLY; Returns the date and time the tag was added. + Timestamp *time.Time + + // READ-ONLY; Returns the User Principal Name of the user who added the tag. + Upn *string +} + +// TrackedResource - The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' +// and a 'location' +type TrackedResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// UpdateHistoryProperty - An update history of the ImmutabilityPolicy of a blob container. +type UpdateHistoryProperty struct { + // This property can only be changed for unlocked time-based retention policies. When enabled, new blocks can be written to + // an append blob while maintaining immutability protection and compliance. Only + // new blocks can be added and any existing blocks cannot be modified or deleted. This property cannot be changed with ExtendImmutabilityPolicy + // API. + AllowProtectedAppendWrites *bool + + // This property can only be changed for unlocked time-based retention policies. When enabled, new blocks can be written to + // both 'Append and Bock Blobs' while maintaining immutability protection and + // compliance. Only new blocks can be added and any existing blocks cannot be modified or deleted. This property cannot be + // changed with ExtendImmutabilityPolicy API. The 'allowProtectedAppendWrites' and + // 'allowProtectedAppendWritesAll' properties are mutually exclusive. + AllowProtectedAppendWritesAll *bool + + // READ-ONLY; The immutability period for the blobs in the container since the policy creation, in days. + ImmutabilityPeriodSinceCreationInDays *int32 + + // READ-ONLY; Returns the Object ID of the user who updated the ImmutabilityPolicy. + ObjectIdentifier *string + + // READ-ONLY; Returns the Tenant ID that issued the token for the user who updated the ImmutabilityPolicy. + TenantID *string + + // READ-ONLY; Returns the date and time the ImmutabilityPolicy was updated. + Timestamp *time.Time + + // READ-ONLY; The ImmutabilityPolicy update type of a blob container, possible values include: put, lock and extend. + Update *ImmutabilityPolicyUpdateType + + // READ-ONLY; Returns the User Principal Name of the user who updated the ImmutabilityPolicy. + Upn *string +} + +// Usage - Describes Storage Resource Usage. +type Usage struct { + // READ-ONLY; Gets the current count of the allocated resources in the subscription. + CurrentValue *int32 + + // READ-ONLY; Gets the maximum count of the resources that can be allocated in the subscription. + Limit *int32 + + // READ-ONLY; Gets the name of the type of usage. + Name *UsageName + + // READ-ONLY; Gets the unit of measurement. + Unit *UsageUnit +} + +// UsageListResult - The response from the List Usages operation. +type UsageListResult struct { + // Gets or sets the list of Storage Resource Usages. + Value []*Usage +} + +// UsageName - The usage names that can be used; currently limited to StorageAccount. +type UsageName struct { + // READ-ONLY; Gets a localized string describing the resource name. + LocalizedValue *string + + // READ-ONLY; Gets a string describing the resource name. + Value *string +} + +// UserAssignedIdentity for the resource. +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the identity. + ClientID *string + + // READ-ONLY; The principal ID of the identity. + PrincipalID *string +} + +// VirtualNetworkRule - Virtual Network rule. +type VirtualNetworkRule struct { + // REQUIRED; Resource ID of a subnet, for example: /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{vnetName}/subnets/{subnetName}. + VirtualNetworkResourceID *string + + // The action of virtual network rule. + Action *string + + // Gets the state of virtual network rule. + State *State +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models_serde.go new file mode 100644 index 0000000000..0c96a09021 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/models_serde.go @@ -0,0 +1,6851 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AccessPolicy. +func (a AccessPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiryTime", a.ExpiryTime) + populate(objectMap, "permission", a.Permission) + populateDateTimeRFC3339(objectMap, "startTime", a.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccessPolicy. +func (a *AccessPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiryTime": + err = unpopulateDateTimeRFC3339(val, "ExpiryTime", &a.ExpiryTime) + delete(rawMsg, key) + case "permission": + err = unpopulate(val, "Permission", &a.Permission) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &a.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Account. +func (a Account) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", a.ExtendedLocation) + populate(objectMap, "id", a.ID) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Account. +func (a *Account) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &a.ExtendedLocation) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountCheckNameAvailabilityParameters. +func (a AccountCheckNameAvailabilityParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + objectMap["type"] = "Microsoft.Storage/storageAccounts" + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountCheckNameAvailabilityParameters. +func (a *AccountCheckNameAvailabilityParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountCreateParameters. +func (a AccountCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extendedLocation", a.ExtendedLocation) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "location", a.Location) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountCreateParameters. +func (a *AccountCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &a.ExtendedLocation) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountImmutabilityPolicyProperties. +func (a AccountImmutabilityPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowProtectedAppendWrites", a.AllowProtectedAppendWrites) + populate(objectMap, "immutabilityPeriodSinceCreationInDays", a.ImmutabilityPeriodSinceCreationInDays) + populate(objectMap, "state", a.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountImmutabilityPolicyProperties. +func (a *AccountImmutabilityPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowProtectedAppendWrites": + err = unpopulate(val, "AllowProtectedAppendWrites", &a.AllowProtectedAppendWrites) + delete(rawMsg, key) + case "immutabilityPeriodSinceCreationInDays": + err = unpopulate(val, "ImmutabilityPeriodSinceCreationInDays", &a.ImmutabilityPeriodSinceCreationInDays) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &a.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountInternetEndpoints. +func (a AccountInternetEndpoints) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blob", a.Blob) + populate(objectMap, "dfs", a.Dfs) + populate(objectMap, "file", a.File) + populate(objectMap, "web", a.Web) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountInternetEndpoints. +func (a *AccountInternetEndpoints) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blob": + err = unpopulate(val, "Blob", &a.Blob) + delete(rawMsg, key) + case "dfs": + err = unpopulate(val, "Dfs", &a.Dfs) + delete(rawMsg, key) + case "file": + err = unpopulate(val, "File", &a.File) + delete(rawMsg, key) + case "web": + err = unpopulate(val, "Web", &a.Web) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountKey. +func (a AccountKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "creationTime", a.CreationTime) + populate(objectMap, "keyName", a.KeyName) + populate(objectMap, "permissions", a.Permissions) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountKey. +func (a *AccountKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &a.CreationTime) + delete(rawMsg, key) + case "keyName": + err = unpopulate(val, "KeyName", &a.KeyName) + delete(rawMsg, key) + case "permissions": + err = unpopulate(val, "Permissions", &a.Permissions) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountListKeysResult. +func (a AccountListKeysResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keys", a.Keys) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountListKeysResult. +func (a *AccountListKeysResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keys": + err = unpopulate(val, "Keys", &a.Keys) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountListResult. +func (a AccountListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountListResult. +func (a *AccountListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountMicrosoftEndpoints. +func (a AccountMicrosoftEndpoints) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blob", a.Blob) + populate(objectMap, "dfs", a.Dfs) + populate(objectMap, "file", a.File) + populate(objectMap, "queue", a.Queue) + populate(objectMap, "table", a.Table) + populate(objectMap, "web", a.Web) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountMicrosoftEndpoints. +func (a *AccountMicrosoftEndpoints) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blob": + err = unpopulate(val, "Blob", &a.Blob) + delete(rawMsg, key) + case "dfs": + err = unpopulate(val, "Dfs", &a.Dfs) + delete(rawMsg, key) + case "file": + err = unpopulate(val, "File", &a.File) + delete(rawMsg, key) + case "queue": + err = unpopulate(val, "Queue", &a.Queue) + delete(rawMsg, key) + case "table": + err = unpopulate(val, "Table", &a.Table) + delete(rawMsg, key) + case "web": + err = unpopulate(val, "Web", &a.Web) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountMigration. +func (a AccountMigration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.StorageAccountMigrationDetails) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountMigration. +func (a *AccountMigration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "StorageAccountMigrationDetails", &a.StorageAccountMigrationDetails) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountMigrationProperties. +func (a AccountMigrationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "migrationFailedDetailedReason", a.MigrationFailedDetailedReason) + populate(objectMap, "migrationFailedReason", a.MigrationFailedReason) + populate(objectMap, "migrationStatus", a.MigrationStatus) + populate(objectMap, "targetSkuName", a.TargetSKUName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountMigrationProperties. +func (a *AccountMigrationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "migrationFailedDetailedReason": + err = unpopulate(val, "MigrationFailedDetailedReason", &a.MigrationFailedDetailedReason) + delete(rawMsg, key) + case "migrationFailedReason": + err = unpopulate(val, "MigrationFailedReason", &a.MigrationFailedReason) + delete(rawMsg, key) + case "migrationStatus": + err = unpopulate(val, "MigrationStatus", &a.MigrationStatus) + delete(rawMsg, key) + case "targetSkuName": + err = unpopulate(val, "TargetSKUName", &a.TargetSKUName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountProperties. +func (a AccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessTier", a.AccessTier) + populate(objectMap, "accountMigrationInProgress", a.AccountMigrationInProgress) + populate(objectMap, "allowBlobPublicAccess", a.AllowBlobPublicAccess) + populate(objectMap, "allowCrossTenantReplication", a.AllowCrossTenantReplication) + populate(objectMap, "allowSharedKeyAccess", a.AllowSharedKeyAccess) + populate(objectMap, "allowedCopyScope", a.AllowedCopyScope) + populate(objectMap, "azureFilesIdentityBasedAuthentication", a.AzureFilesIdentityBasedAuthentication) + populate(objectMap, "blobRestoreStatus", a.BlobRestoreStatus) + populateDateTimeRFC3339(objectMap, "creationTime", a.CreationTime) + populate(objectMap, "customDomain", a.CustomDomain) + populate(objectMap, "dnsEndpointType", a.DNSEndpointType) + populate(objectMap, "defaultToOAuthAuthentication", a.DefaultToOAuthAuthentication) + populate(objectMap, "supportsHttpsTrafficOnly", a.EnableHTTPSTrafficOnly) + populate(objectMap, "isNfsV3Enabled", a.EnableNfsV3) + populate(objectMap, "encryption", a.Encryption) + populate(objectMap, "failoverInProgress", a.FailoverInProgress) + populate(objectMap, "geoReplicationStats", a.GeoReplicationStats) + populate(objectMap, "immutableStorageWithVersioning", a.ImmutableStorageWithVersioning) + populate(objectMap, "isHnsEnabled", a.IsHnsEnabled) + populate(objectMap, "isLocalUserEnabled", a.IsLocalUserEnabled) + populate(objectMap, "isSkuConversionBlocked", a.IsSKUConversionBlocked) + populate(objectMap, "isSftpEnabled", a.IsSftpEnabled) + populate(objectMap, "keyCreationTime", a.KeyCreationTime) + populate(objectMap, "keyPolicy", a.KeyPolicy) + populate(objectMap, "largeFileSharesState", a.LargeFileSharesState) + populateDateTimeRFC3339(objectMap, "lastGeoFailoverTime", a.LastGeoFailoverTime) + populate(objectMap, "minimumTlsVersion", a.MinimumTLSVersion) + populate(objectMap, "networkAcls", a.NetworkRuleSet) + populate(objectMap, "primaryEndpoints", a.PrimaryEndpoints) + populate(objectMap, "primaryLocation", a.PrimaryLocation) + populate(objectMap, "privateEndpointConnections", a.PrivateEndpointConnections) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "publicNetworkAccess", a.PublicNetworkAccess) + populate(objectMap, "routingPreference", a.RoutingPreference) + populate(objectMap, "sasPolicy", a.SasPolicy) + populate(objectMap, "secondaryEndpoints", a.SecondaryEndpoints) + populate(objectMap, "secondaryLocation", a.SecondaryLocation) + populate(objectMap, "statusOfPrimary", a.StatusOfPrimary) + populate(objectMap, "statusOfSecondary", a.StatusOfSecondary) + populate(objectMap, "storageAccountSkuConversionStatus", a.StorageAccountSKUConversionStatus) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountProperties. +func (a *AccountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessTier": + err = unpopulate(val, "AccessTier", &a.AccessTier) + delete(rawMsg, key) + case "accountMigrationInProgress": + err = unpopulate(val, "AccountMigrationInProgress", &a.AccountMigrationInProgress) + delete(rawMsg, key) + case "allowBlobPublicAccess": + err = unpopulate(val, "AllowBlobPublicAccess", &a.AllowBlobPublicAccess) + delete(rawMsg, key) + case "allowCrossTenantReplication": + err = unpopulate(val, "AllowCrossTenantReplication", &a.AllowCrossTenantReplication) + delete(rawMsg, key) + case "allowSharedKeyAccess": + err = unpopulate(val, "AllowSharedKeyAccess", &a.AllowSharedKeyAccess) + delete(rawMsg, key) + case "allowedCopyScope": + err = unpopulate(val, "AllowedCopyScope", &a.AllowedCopyScope) + delete(rawMsg, key) + case "azureFilesIdentityBasedAuthentication": + err = unpopulate(val, "AzureFilesIdentityBasedAuthentication", &a.AzureFilesIdentityBasedAuthentication) + delete(rawMsg, key) + case "blobRestoreStatus": + err = unpopulate(val, "BlobRestoreStatus", &a.BlobRestoreStatus) + delete(rawMsg, key) + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &a.CreationTime) + delete(rawMsg, key) + case "customDomain": + err = unpopulate(val, "CustomDomain", &a.CustomDomain) + delete(rawMsg, key) + case "dnsEndpointType": + err = unpopulate(val, "DNSEndpointType", &a.DNSEndpointType) + delete(rawMsg, key) + case "defaultToOAuthAuthentication": + err = unpopulate(val, "DefaultToOAuthAuthentication", &a.DefaultToOAuthAuthentication) + delete(rawMsg, key) + case "supportsHttpsTrafficOnly": + err = unpopulate(val, "EnableHTTPSTrafficOnly", &a.EnableHTTPSTrafficOnly) + delete(rawMsg, key) + case "isNfsV3Enabled": + err = unpopulate(val, "EnableNfsV3", &a.EnableNfsV3) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &a.Encryption) + delete(rawMsg, key) + case "failoverInProgress": + err = unpopulate(val, "FailoverInProgress", &a.FailoverInProgress) + delete(rawMsg, key) + case "geoReplicationStats": + err = unpopulate(val, "GeoReplicationStats", &a.GeoReplicationStats) + delete(rawMsg, key) + case "immutableStorageWithVersioning": + err = unpopulate(val, "ImmutableStorageWithVersioning", &a.ImmutableStorageWithVersioning) + delete(rawMsg, key) + case "isHnsEnabled": + err = unpopulate(val, "IsHnsEnabled", &a.IsHnsEnabled) + delete(rawMsg, key) + case "isLocalUserEnabled": + err = unpopulate(val, "IsLocalUserEnabled", &a.IsLocalUserEnabled) + delete(rawMsg, key) + case "isSkuConversionBlocked": + err = unpopulate(val, "IsSKUConversionBlocked", &a.IsSKUConversionBlocked) + delete(rawMsg, key) + case "isSftpEnabled": + err = unpopulate(val, "IsSftpEnabled", &a.IsSftpEnabled) + delete(rawMsg, key) + case "keyCreationTime": + err = unpopulate(val, "KeyCreationTime", &a.KeyCreationTime) + delete(rawMsg, key) + case "keyPolicy": + err = unpopulate(val, "KeyPolicy", &a.KeyPolicy) + delete(rawMsg, key) + case "largeFileSharesState": + err = unpopulate(val, "LargeFileSharesState", &a.LargeFileSharesState) + delete(rawMsg, key) + case "lastGeoFailoverTime": + err = unpopulateDateTimeRFC3339(val, "LastGeoFailoverTime", &a.LastGeoFailoverTime) + delete(rawMsg, key) + case "minimumTlsVersion": + err = unpopulate(val, "MinimumTLSVersion", &a.MinimumTLSVersion) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkRuleSet", &a.NetworkRuleSet) + delete(rawMsg, key) + case "primaryEndpoints": + err = unpopulate(val, "PrimaryEndpoints", &a.PrimaryEndpoints) + delete(rawMsg, key) + case "primaryLocation": + err = unpopulate(val, "PrimaryLocation", &a.PrimaryLocation) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &a.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &a.PublicNetworkAccess) + delete(rawMsg, key) + case "routingPreference": + err = unpopulate(val, "RoutingPreference", &a.RoutingPreference) + delete(rawMsg, key) + case "sasPolicy": + err = unpopulate(val, "SasPolicy", &a.SasPolicy) + delete(rawMsg, key) + case "secondaryEndpoints": + err = unpopulate(val, "SecondaryEndpoints", &a.SecondaryEndpoints) + delete(rawMsg, key) + case "secondaryLocation": + err = unpopulate(val, "SecondaryLocation", &a.SecondaryLocation) + delete(rawMsg, key) + case "statusOfPrimary": + err = unpopulate(val, "StatusOfPrimary", &a.StatusOfPrimary) + delete(rawMsg, key) + case "statusOfSecondary": + err = unpopulate(val, "StatusOfSecondary", &a.StatusOfSecondary) + delete(rawMsg, key) + case "storageAccountSkuConversionStatus": + err = unpopulate(val, "StorageAccountSKUConversionStatus", &a.StorageAccountSKUConversionStatus) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountPropertiesCreateParameters. +func (a AccountPropertiesCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessTier", a.AccessTier) + populate(objectMap, "allowBlobPublicAccess", a.AllowBlobPublicAccess) + populate(objectMap, "allowCrossTenantReplication", a.AllowCrossTenantReplication) + populate(objectMap, "allowSharedKeyAccess", a.AllowSharedKeyAccess) + populate(objectMap, "allowedCopyScope", a.AllowedCopyScope) + populate(objectMap, "azureFilesIdentityBasedAuthentication", a.AzureFilesIdentityBasedAuthentication) + populate(objectMap, "customDomain", a.CustomDomain) + populate(objectMap, "dnsEndpointType", a.DNSEndpointType) + populate(objectMap, "defaultToOAuthAuthentication", a.DefaultToOAuthAuthentication) + populate(objectMap, "supportsHttpsTrafficOnly", a.EnableHTTPSTrafficOnly) + populate(objectMap, "isNfsV3Enabled", a.EnableNfsV3) + populate(objectMap, "encryption", a.Encryption) + populate(objectMap, "immutableStorageWithVersioning", a.ImmutableStorageWithVersioning) + populate(objectMap, "isHnsEnabled", a.IsHnsEnabled) + populate(objectMap, "isLocalUserEnabled", a.IsLocalUserEnabled) + populate(objectMap, "isSftpEnabled", a.IsSftpEnabled) + populate(objectMap, "keyPolicy", a.KeyPolicy) + populate(objectMap, "largeFileSharesState", a.LargeFileSharesState) + populate(objectMap, "minimumTlsVersion", a.MinimumTLSVersion) + populate(objectMap, "networkAcls", a.NetworkRuleSet) + populate(objectMap, "publicNetworkAccess", a.PublicNetworkAccess) + populate(objectMap, "routingPreference", a.RoutingPreference) + populate(objectMap, "sasPolicy", a.SasPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountPropertiesCreateParameters. +func (a *AccountPropertiesCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessTier": + err = unpopulate(val, "AccessTier", &a.AccessTier) + delete(rawMsg, key) + case "allowBlobPublicAccess": + err = unpopulate(val, "AllowBlobPublicAccess", &a.AllowBlobPublicAccess) + delete(rawMsg, key) + case "allowCrossTenantReplication": + err = unpopulate(val, "AllowCrossTenantReplication", &a.AllowCrossTenantReplication) + delete(rawMsg, key) + case "allowSharedKeyAccess": + err = unpopulate(val, "AllowSharedKeyAccess", &a.AllowSharedKeyAccess) + delete(rawMsg, key) + case "allowedCopyScope": + err = unpopulate(val, "AllowedCopyScope", &a.AllowedCopyScope) + delete(rawMsg, key) + case "azureFilesIdentityBasedAuthentication": + err = unpopulate(val, "AzureFilesIdentityBasedAuthentication", &a.AzureFilesIdentityBasedAuthentication) + delete(rawMsg, key) + case "customDomain": + err = unpopulate(val, "CustomDomain", &a.CustomDomain) + delete(rawMsg, key) + case "dnsEndpointType": + err = unpopulate(val, "DNSEndpointType", &a.DNSEndpointType) + delete(rawMsg, key) + case "defaultToOAuthAuthentication": + err = unpopulate(val, "DefaultToOAuthAuthentication", &a.DefaultToOAuthAuthentication) + delete(rawMsg, key) + case "supportsHttpsTrafficOnly": + err = unpopulate(val, "EnableHTTPSTrafficOnly", &a.EnableHTTPSTrafficOnly) + delete(rawMsg, key) + case "isNfsV3Enabled": + err = unpopulate(val, "EnableNfsV3", &a.EnableNfsV3) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &a.Encryption) + delete(rawMsg, key) + case "immutableStorageWithVersioning": + err = unpopulate(val, "ImmutableStorageWithVersioning", &a.ImmutableStorageWithVersioning) + delete(rawMsg, key) + case "isHnsEnabled": + err = unpopulate(val, "IsHnsEnabled", &a.IsHnsEnabled) + delete(rawMsg, key) + case "isLocalUserEnabled": + err = unpopulate(val, "IsLocalUserEnabled", &a.IsLocalUserEnabled) + delete(rawMsg, key) + case "isSftpEnabled": + err = unpopulate(val, "IsSftpEnabled", &a.IsSftpEnabled) + delete(rawMsg, key) + case "keyPolicy": + err = unpopulate(val, "KeyPolicy", &a.KeyPolicy) + delete(rawMsg, key) + case "largeFileSharesState": + err = unpopulate(val, "LargeFileSharesState", &a.LargeFileSharesState) + delete(rawMsg, key) + case "minimumTlsVersion": + err = unpopulate(val, "MinimumTLSVersion", &a.MinimumTLSVersion) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkRuleSet", &a.NetworkRuleSet) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &a.PublicNetworkAccess) + delete(rawMsg, key) + case "routingPreference": + err = unpopulate(val, "RoutingPreference", &a.RoutingPreference) + delete(rawMsg, key) + case "sasPolicy": + err = unpopulate(val, "SasPolicy", &a.SasPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountPropertiesUpdateParameters. +func (a AccountPropertiesUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessTier", a.AccessTier) + populate(objectMap, "allowBlobPublicAccess", a.AllowBlobPublicAccess) + populate(objectMap, "allowCrossTenantReplication", a.AllowCrossTenantReplication) + populate(objectMap, "allowSharedKeyAccess", a.AllowSharedKeyAccess) + populate(objectMap, "allowedCopyScope", a.AllowedCopyScope) + populate(objectMap, "azureFilesIdentityBasedAuthentication", a.AzureFilesIdentityBasedAuthentication) + populate(objectMap, "customDomain", a.CustomDomain) + populate(objectMap, "dnsEndpointType", a.DNSEndpointType) + populate(objectMap, "defaultToOAuthAuthentication", a.DefaultToOAuthAuthentication) + populate(objectMap, "supportsHttpsTrafficOnly", a.EnableHTTPSTrafficOnly) + populate(objectMap, "encryption", a.Encryption) + populate(objectMap, "immutableStorageWithVersioning", a.ImmutableStorageWithVersioning) + populate(objectMap, "isLocalUserEnabled", a.IsLocalUserEnabled) + populate(objectMap, "isSftpEnabled", a.IsSftpEnabled) + populate(objectMap, "keyPolicy", a.KeyPolicy) + populate(objectMap, "largeFileSharesState", a.LargeFileSharesState) + populate(objectMap, "minimumTlsVersion", a.MinimumTLSVersion) + populate(objectMap, "networkAcls", a.NetworkRuleSet) + populate(objectMap, "publicNetworkAccess", a.PublicNetworkAccess) + populate(objectMap, "routingPreference", a.RoutingPreference) + populate(objectMap, "sasPolicy", a.SasPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountPropertiesUpdateParameters. +func (a *AccountPropertiesUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessTier": + err = unpopulate(val, "AccessTier", &a.AccessTier) + delete(rawMsg, key) + case "allowBlobPublicAccess": + err = unpopulate(val, "AllowBlobPublicAccess", &a.AllowBlobPublicAccess) + delete(rawMsg, key) + case "allowCrossTenantReplication": + err = unpopulate(val, "AllowCrossTenantReplication", &a.AllowCrossTenantReplication) + delete(rawMsg, key) + case "allowSharedKeyAccess": + err = unpopulate(val, "AllowSharedKeyAccess", &a.AllowSharedKeyAccess) + delete(rawMsg, key) + case "allowedCopyScope": + err = unpopulate(val, "AllowedCopyScope", &a.AllowedCopyScope) + delete(rawMsg, key) + case "azureFilesIdentityBasedAuthentication": + err = unpopulate(val, "AzureFilesIdentityBasedAuthentication", &a.AzureFilesIdentityBasedAuthentication) + delete(rawMsg, key) + case "customDomain": + err = unpopulate(val, "CustomDomain", &a.CustomDomain) + delete(rawMsg, key) + case "dnsEndpointType": + err = unpopulate(val, "DNSEndpointType", &a.DNSEndpointType) + delete(rawMsg, key) + case "defaultToOAuthAuthentication": + err = unpopulate(val, "DefaultToOAuthAuthentication", &a.DefaultToOAuthAuthentication) + delete(rawMsg, key) + case "supportsHttpsTrafficOnly": + err = unpopulate(val, "EnableHTTPSTrafficOnly", &a.EnableHTTPSTrafficOnly) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &a.Encryption) + delete(rawMsg, key) + case "immutableStorageWithVersioning": + err = unpopulate(val, "ImmutableStorageWithVersioning", &a.ImmutableStorageWithVersioning) + delete(rawMsg, key) + case "isLocalUserEnabled": + err = unpopulate(val, "IsLocalUserEnabled", &a.IsLocalUserEnabled) + delete(rawMsg, key) + case "isSftpEnabled": + err = unpopulate(val, "IsSftpEnabled", &a.IsSftpEnabled) + delete(rawMsg, key) + case "keyPolicy": + err = unpopulate(val, "KeyPolicy", &a.KeyPolicy) + delete(rawMsg, key) + case "largeFileSharesState": + err = unpopulate(val, "LargeFileSharesState", &a.LargeFileSharesState) + delete(rawMsg, key) + case "minimumTlsVersion": + err = unpopulate(val, "MinimumTLSVersion", &a.MinimumTLSVersion) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkRuleSet", &a.NetworkRuleSet) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &a.PublicNetworkAccess) + delete(rawMsg, key) + case "routingPreference": + err = unpopulate(val, "RoutingPreference", &a.RoutingPreference) + delete(rawMsg, key) + case "sasPolicy": + err = unpopulate(val, "SasPolicy", &a.SasPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountRegenerateKeyParameters. +func (a AccountRegenerateKeyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyName", a.KeyName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountRegenerateKeyParameters. +func (a *AccountRegenerateKeyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyName": + err = unpopulate(val, "KeyName", &a.KeyName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSKUConversionStatus. +func (a AccountSKUConversionStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endTime", a.EndTime) + populate(objectMap, "skuConversionStatus", a.SKUConversionStatus) + populate(objectMap, "startTime", a.StartTime) + populate(objectMap, "targetSkuName", a.TargetSKUName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSKUConversionStatus. +func (a *AccountSKUConversionStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulate(val, "EndTime", &a.EndTime) + delete(rawMsg, key) + case "skuConversionStatus": + err = unpopulate(val, "SKUConversionStatus", &a.SKUConversionStatus) + delete(rawMsg, key) + case "startTime": + err = unpopulate(val, "StartTime", &a.StartTime) + delete(rawMsg, key) + case "targetSkuName": + err = unpopulate(val, "TargetSKUName", &a.TargetSKUName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSasParameters. +func (a AccountSasParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "signedIp", a.IPAddressOrRange) + populate(objectMap, "keyToSign", a.KeyToSign) + populate(objectMap, "signedPermission", a.Permissions) + populate(objectMap, "signedProtocol", a.Protocols) + populate(objectMap, "signedResourceTypes", a.ResourceTypes) + populate(objectMap, "signedServices", a.Services) + populateDateTimeRFC3339(objectMap, "signedExpiry", a.SharedAccessExpiryTime) + populateDateTimeRFC3339(objectMap, "signedStart", a.SharedAccessStartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSasParameters. +func (a *AccountSasParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "signedIp": + err = unpopulate(val, "IPAddressOrRange", &a.IPAddressOrRange) + delete(rawMsg, key) + case "keyToSign": + err = unpopulate(val, "KeyToSign", &a.KeyToSign) + delete(rawMsg, key) + case "signedPermission": + err = unpopulate(val, "Permissions", &a.Permissions) + delete(rawMsg, key) + case "signedProtocol": + err = unpopulate(val, "Protocols", &a.Protocols) + delete(rawMsg, key) + case "signedResourceTypes": + err = unpopulate(val, "ResourceTypes", &a.ResourceTypes) + delete(rawMsg, key) + case "signedServices": + err = unpopulate(val, "Services", &a.Services) + delete(rawMsg, key) + case "signedExpiry": + err = unpopulateDateTimeRFC3339(val, "SharedAccessExpiryTime", &a.SharedAccessExpiryTime) + delete(rawMsg, key) + case "signedStart": + err = unpopulateDateTimeRFC3339(val, "SharedAccessStartTime", &a.SharedAccessStartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountUpdateParameters. +func (a AccountUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountUpdateParameters. +func (a *AccountUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ActiveDirectoryProperties. +func (a ActiveDirectoryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountType", a.AccountType) + populate(objectMap, "azureStorageSid", a.AzureStorageSid) + populate(objectMap, "domainGuid", a.DomainGUID) + populate(objectMap, "domainName", a.DomainName) + populate(objectMap, "domainSid", a.DomainSid) + populate(objectMap, "forestName", a.ForestName) + populate(objectMap, "netBiosDomainName", a.NetBiosDomainName) + populate(objectMap, "samAccountName", a.SamAccountName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActiveDirectoryProperties. +func (a *ActiveDirectoryProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accountType": + err = unpopulate(val, "AccountType", &a.AccountType) + delete(rawMsg, key) + case "azureStorageSid": + err = unpopulate(val, "AzureStorageSid", &a.AzureStorageSid) + delete(rawMsg, key) + case "domainGuid": + err = unpopulate(val, "DomainGUID", &a.DomainGUID) + delete(rawMsg, key) + case "domainName": + err = unpopulate(val, "DomainName", &a.DomainName) + delete(rawMsg, key) + case "domainSid": + err = unpopulate(val, "DomainSid", &a.DomainSid) + delete(rawMsg, key) + case "forestName": + err = unpopulate(val, "ForestName", &a.ForestName) + delete(rawMsg, key) + case "netBiosDomainName": + err = unpopulate(val, "NetBiosDomainName", &a.NetBiosDomainName) + delete(rawMsg, key) + case "samAccountName": + err = unpopulate(val, "SamAccountName", &a.SamAccountName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureEntityResource. +func (a AzureEntityResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureEntityResource. +func (a *AzureEntityResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &a.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureFilesIdentityBasedAuthentication. +func (a AzureFilesIdentityBasedAuthentication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activeDirectoryProperties", a.ActiveDirectoryProperties) + populate(objectMap, "defaultSharePermission", a.DefaultSharePermission) + populate(objectMap, "directoryServiceOptions", a.DirectoryServiceOptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFilesIdentityBasedAuthentication. +func (a *AzureFilesIdentityBasedAuthentication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "activeDirectoryProperties": + err = unpopulate(val, "ActiveDirectoryProperties", &a.ActiveDirectoryProperties) + delete(rawMsg, key) + case "defaultSharePermission": + err = unpopulate(val, "DefaultSharePermission", &a.DefaultSharePermission) + delete(rawMsg, key) + case "directoryServiceOptions": + err = unpopulate(val, "DirectoryServiceOptions", &a.DirectoryServiceOptions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobContainer. +func (b BlobContainer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", b.ContainerProperties) + populate(objectMap, "etag", b.Etag) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobContainer. +func (b *BlobContainer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "ContainerProperties", &b.ContainerProperties) + delete(rawMsg, key) + case "etag": + err = unpopulate(val, "Etag", &b.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryCreationTime. +func (b BlobInventoryCreationTime) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "lastNDays", b.LastNDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryCreationTime. +func (b *BlobInventoryCreationTime) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lastNDays": + err = unpopulate(val, "LastNDays", &b.LastNDays) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryPolicy. +func (b BlobInventoryPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "systemData", b.SystemData) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryPolicy. +func (b *BlobInventoryPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &b.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &b.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryPolicyDefinition. +func (b BlobInventoryPolicyDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filters", b.Filters) + populate(objectMap, "format", b.Format) + populate(objectMap, "objectType", b.ObjectType) + populate(objectMap, "schedule", b.Schedule) + populate(objectMap, "schemaFields", b.SchemaFields) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryPolicyDefinition. +func (b *BlobInventoryPolicyDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "filters": + err = unpopulate(val, "Filters", &b.Filters) + delete(rawMsg, key) + case "format": + err = unpopulate(val, "Format", &b.Format) + delete(rawMsg, key) + case "objectType": + err = unpopulate(val, "ObjectType", &b.ObjectType) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &b.Schedule) + delete(rawMsg, key) + case "schemaFields": + err = unpopulate(val, "SchemaFields", &b.SchemaFields) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryPolicyFilter. +func (b BlobInventoryPolicyFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobTypes", b.BlobTypes) + populate(objectMap, "creationTime", b.CreationTime) + populate(objectMap, "excludePrefix", b.ExcludePrefix) + populate(objectMap, "includeBlobVersions", b.IncludeBlobVersions) + populate(objectMap, "includeDeleted", b.IncludeDeleted) + populate(objectMap, "includeSnapshots", b.IncludeSnapshots) + populate(objectMap, "prefixMatch", b.PrefixMatch) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryPolicyFilter. +func (b *BlobInventoryPolicyFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blobTypes": + err = unpopulate(val, "BlobTypes", &b.BlobTypes) + delete(rawMsg, key) + case "creationTime": + err = unpopulate(val, "CreationTime", &b.CreationTime) + delete(rawMsg, key) + case "excludePrefix": + err = unpopulate(val, "ExcludePrefix", &b.ExcludePrefix) + delete(rawMsg, key) + case "includeBlobVersions": + err = unpopulate(val, "IncludeBlobVersions", &b.IncludeBlobVersions) + delete(rawMsg, key) + case "includeDeleted": + err = unpopulate(val, "IncludeDeleted", &b.IncludeDeleted) + delete(rawMsg, key) + case "includeSnapshots": + err = unpopulate(val, "IncludeSnapshots", &b.IncludeSnapshots) + delete(rawMsg, key) + case "prefixMatch": + err = unpopulate(val, "PrefixMatch", &b.PrefixMatch) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryPolicyProperties. +func (b BlobInventoryPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", b.LastModifiedTime) + populate(objectMap, "policy", b.Policy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryPolicyProperties. +func (b *BlobInventoryPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &b.LastModifiedTime) + delete(rawMsg, key) + case "policy": + err = unpopulate(val, "Policy", &b.Policy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryPolicyRule. +func (b BlobInventoryPolicyRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "definition", b.Definition) + populate(objectMap, "destination", b.Destination) + populate(objectMap, "enabled", b.Enabled) + populate(objectMap, "name", b.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryPolicyRule. +func (b *BlobInventoryPolicyRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "definition": + err = unpopulate(val, "Definition", &b.Definition) + delete(rawMsg, key) + case "destination": + err = unpopulate(val, "Destination", &b.Destination) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &b.Enabled) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobInventoryPolicySchema. +func (b BlobInventoryPolicySchema) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destination", b.Destination) + populate(objectMap, "enabled", b.Enabled) + populate(objectMap, "rules", b.Rules) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobInventoryPolicySchema. +func (b *BlobInventoryPolicySchema) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "destination": + err = unpopulate(val, "Destination", &b.Destination) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &b.Enabled) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &b.Rules) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobRestoreParameters. +func (b BlobRestoreParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobRanges", b.BlobRanges) + populateDateTimeRFC3339(objectMap, "timeToRestore", b.TimeToRestore) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobRestoreParameters. +func (b *BlobRestoreParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blobRanges": + err = unpopulate(val, "BlobRanges", &b.BlobRanges) + delete(rawMsg, key) + case "timeToRestore": + err = unpopulateDateTimeRFC3339(val, "TimeToRestore", &b.TimeToRestore) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobRestoreRange. +func (b BlobRestoreRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endRange", b.EndRange) + populate(objectMap, "startRange", b.StartRange) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobRestoreRange. +func (b *BlobRestoreRange) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endRange": + err = unpopulate(val, "EndRange", &b.EndRange) + delete(rawMsg, key) + case "startRange": + err = unpopulate(val, "StartRange", &b.StartRange) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobRestoreStatus. +func (b BlobRestoreStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "failureReason", b.FailureReason) + populate(objectMap, "parameters", b.Parameters) + populate(objectMap, "restoreId", b.RestoreID) + populate(objectMap, "status", b.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobRestoreStatus. +func (b *BlobRestoreStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "failureReason": + err = unpopulate(val, "FailureReason", &b.FailureReason) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &b.Parameters) + delete(rawMsg, key) + case "restoreId": + err = unpopulate(val, "RestoreID", &b.RestoreID) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &b.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobServiceItems. +func (b BlobServiceItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobServiceItems. +func (b *BlobServiceItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &b.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobServiceProperties. +func (b BlobServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", b.BlobServiceProperties) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "sku", b.SKU) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobServiceProperties. +func (b *BlobServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "BlobServiceProperties", &b.BlobServiceProperties) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &b.SKU) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobServicePropertiesProperties. +func (b BlobServicePropertiesProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticSnapshotPolicyEnabled", b.AutomaticSnapshotPolicyEnabled) + populate(objectMap, "changeFeed", b.ChangeFeed) + populate(objectMap, "containerDeleteRetentionPolicy", b.ContainerDeleteRetentionPolicy) + populate(objectMap, "cors", b.Cors) + populate(objectMap, "defaultServiceVersion", b.DefaultServiceVersion) + populate(objectMap, "deleteRetentionPolicy", b.DeleteRetentionPolicy) + populate(objectMap, "isVersioningEnabled", b.IsVersioningEnabled) + populate(objectMap, "lastAccessTimeTrackingPolicy", b.LastAccessTimeTrackingPolicy) + populate(objectMap, "restorePolicy", b.RestorePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobServicePropertiesProperties. +func (b *BlobServicePropertiesProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "automaticSnapshotPolicyEnabled": + err = unpopulate(val, "AutomaticSnapshotPolicyEnabled", &b.AutomaticSnapshotPolicyEnabled) + delete(rawMsg, key) + case "changeFeed": + err = unpopulate(val, "ChangeFeed", &b.ChangeFeed) + delete(rawMsg, key) + case "containerDeleteRetentionPolicy": + err = unpopulate(val, "ContainerDeleteRetentionPolicy", &b.ContainerDeleteRetentionPolicy) + delete(rawMsg, key) + case "cors": + err = unpopulate(val, "Cors", &b.Cors) + delete(rawMsg, key) + case "defaultServiceVersion": + err = unpopulate(val, "DefaultServiceVersion", &b.DefaultServiceVersion) + delete(rawMsg, key) + case "deleteRetentionPolicy": + err = unpopulate(val, "DeleteRetentionPolicy", &b.DeleteRetentionPolicy) + delete(rawMsg, key) + case "isVersioningEnabled": + err = unpopulate(val, "IsVersioningEnabled", &b.IsVersioningEnabled) + delete(rawMsg, key) + case "lastAccessTimeTrackingPolicy": + err = unpopulate(val, "LastAccessTimeTrackingPolicy", &b.LastAccessTimeTrackingPolicy) + delete(rawMsg, key) + case "restorePolicy": + err = unpopulate(val, "RestorePolicy", &b.RestorePolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ChangeFeed. +func (c ChangeFeed) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", c.Enabled) + populate(objectMap, "retentionInDays", c.RetentionInDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChangeFeed. +func (c *ChangeFeed) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &c.Enabled) + delete(rawMsg, key) + case "retentionInDays": + err = unpopulate(val, "RetentionInDays", &c.RetentionInDays) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResult. +func (c CheckNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", c.Message) + populate(objectMap, "nameAvailable", c.NameAvailable) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResult. +func (c *CheckNameAvailabilityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &c.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContainerProperties. +func (c ContainerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultEncryptionScope", c.DefaultEncryptionScope) + populate(objectMap, "deleted", c.Deleted) + populateDateTimeRFC3339(objectMap, "deletedTime", c.DeletedTime) + populate(objectMap, "denyEncryptionScopeOverride", c.DenyEncryptionScopeOverride) + populate(objectMap, "enableNfsV3AllSquash", c.EnableNfsV3AllSquash) + populate(objectMap, "enableNfsV3RootSquash", c.EnableNfsV3RootSquash) + populate(objectMap, "hasImmutabilityPolicy", c.HasImmutabilityPolicy) + populate(objectMap, "hasLegalHold", c.HasLegalHold) + populate(objectMap, "immutabilityPolicy", c.ImmutabilityPolicy) + populate(objectMap, "immutableStorageWithVersioning", c.ImmutableStorageWithVersioning) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", c.LastModifiedTime) + populate(objectMap, "leaseDuration", c.LeaseDuration) + populate(objectMap, "leaseState", c.LeaseState) + populate(objectMap, "leaseStatus", c.LeaseStatus) + populate(objectMap, "legalHold", c.LegalHold) + populate(objectMap, "metadata", c.Metadata) + populate(objectMap, "publicAccess", c.PublicAccess) + populate(objectMap, "remainingRetentionDays", c.RemainingRetentionDays) + populate(objectMap, "version", c.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainerProperties. +func (c *ContainerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "defaultEncryptionScope": + err = unpopulate(val, "DefaultEncryptionScope", &c.DefaultEncryptionScope) + delete(rawMsg, key) + case "deleted": + err = unpopulate(val, "Deleted", &c.Deleted) + delete(rawMsg, key) + case "deletedTime": + err = unpopulateDateTimeRFC3339(val, "DeletedTime", &c.DeletedTime) + delete(rawMsg, key) + case "denyEncryptionScopeOverride": + err = unpopulate(val, "DenyEncryptionScopeOverride", &c.DenyEncryptionScopeOverride) + delete(rawMsg, key) + case "enableNfsV3AllSquash": + err = unpopulate(val, "EnableNfsV3AllSquash", &c.EnableNfsV3AllSquash) + delete(rawMsg, key) + case "enableNfsV3RootSquash": + err = unpopulate(val, "EnableNfsV3RootSquash", &c.EnableNfsV3RootSquash) + delete(rawMsg, key) + case "hasImmutabilityPolicy": + err = unpopulate(val, "HasImmutabilityPolicy", &c.HasImmutabilityPolicy) + delete(rawMsg, key) + case "hasLegalHold": + err = unpopulate(val, "HasLegalHold", &c.HasLegalHold) + delete(rawMsg, key) + case "immutabilityPolicy": + err = unpopulate(val, "ImmutabilityPolicy", &c.ImmutabilityPolicy) + delete(rawMsg, key) + case "immutableStorageWithVersioning": + err = unpopulate(val, "ImmutableStorageWithVersioning", &c.ImmutableStorageWithVersioning) + delete(rawMsg, key) + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &c.LastModifiedTime) + delete(rawMsg, key) + case "leaseDuration": + err = unpopulate(val, "LeaseDuration", &c.LeaseDuration) + delete(rawMsg, key) + case "leaseState": + err = unpopulate(val, "LeaseState", &c.LeaseState) + delete(rawMsg, key) + case "leaseStatus": + err = unpopulate(val, "LeaseStatus", &c.LeaseStatus) + delete(rawMsg, key) + case "legalHold": + err = unpopulate(val, "LegalHold", &c.LegalHold) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &c.Metadata) + delete(rawMsg, key) + case "publicAccess": + err = unpopulate(val, "PublicAccess", &c.PublicAccess) + delete(rawMsg, key) + case "remainingRetentionDays": + err = unpopulate(val, "RemainingRetentionDays", &c.RemainingRetentionDays) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &c.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CorsRule. +func (c CorsRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowedHeaders", c.AllowedHeaders) + populate(objectMap, "allowedMethods", c.AllowedMethods) + populate(objectMap, "allowedOrigins", c.AllowedOrigins) + populate(objectMap, "exposedHeaders", c.ExposedHeaders) + populate(objectMap, "maxAgeInSeconds", c.MaxAgeInSeconds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CorsRule. +func (c *CorsRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowedHeaders": + err = unpopulate(val, "AllowedHeaders", &c.AllowedHeaders) + delete(rawMsg, key) + case "allowedMethods": + err = unpopulate(val, "AllowedMethods", &c.AllowedMethods) + delete(rawMsg, key) + case "allowedOrigins": + err = unpopulate(val, "AllowedOrigins", &c.AllowedOrigins) + delete(rawMsg, key) + case "exposedHeaders": + err = unpopulate(val, "ExposedHeaders", &c.ExposedHeaders) + delete(rawMsg, key) + case "maxAgeInSeconds": + err = unpopulate(val, "MaxAgeInSeconds", &c.MaxAgeInSeconds) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CorsRules. +func (c CorsRules) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "corsRules", c.CorsRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CorsRules. +func (c *CorsRules) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "corsRules": + err = unpopulate(val, "CorsRules", &c.CorsRules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomDomain. +func (c CustomDomain) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "useSubDomainName", c.UseSubDomainName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomDomain. +func (c *CustomDomain) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "useSubDomainName": + err = unpopulate(val, "UseSubDomainName", &c.UseSubDomainName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DateAfterCreation. +func (d DateAfterCreation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "daysAfterCreationGreaterThan", d.DaysAfterCreationGreaterThan) + populate(objectMap, "daysAfterLastTierChangeGreaterThan", d.DaysAfterLastTierChangeGreaterThan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DateAfterCreation. +func (d *DateAfterCreation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "daysAfterCreationGreaterThan": + err = unpopulate(val, "DaysAfterCreationGreaterThan", &d.DaysAfterCreationGreaterThan) + delete(rawMsg, key) + case "daysAfterLastTierChangeGreaterThan": + err = unpopulate(val, "DaysAfterLastTierChangeGreaterThan", &d.DaysAfterLastTierChangeGreaterThan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DateAfterModification. +func (d DateAfterModification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "daysAfterCreationGreaterThan", d.DaysAfterCreationGreaterThan) + populate(objectMap, "daysAfterLastAccessTimeGreaterThan", d.DaysAfterLastAccessTimeGreaterThan) + populate(objectMap, "daysAfterLastTierChangeGreaterThan", d.DaysAfterLastTierChangeGreaterThan) + populate(objectMap, "daysAfterModificationGreaterThan", d.DaysAfterModificationGreaterThan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DateAfterModification. +func (d *DateAfterModification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "daysAfterCreationGreaterThan": + err = unpopulate(val, "DaysAfterCreationGreaterThan", &d.DaysAfterCreationGreaterThan) + delete(rawMsg, key) + case "daysAfterLastAccessTimeGreaterThan": + err = unpopulate(val, "DaysAfterLastAccessTimeGreaterThan", &d.DaysAfterLastAccessTimeGreaterThan) + delete(rawMsg, key) + case "daysAfterLastTierChangeGreaterThan": + err = unpopulate(val, "DaysAfterLastTierChangeGreaterThan", &d.DaysAfterLastTierChangeGreaterThan) + delete(rawMsg, key) + case "daysAfterModificationGreaterThan": + err = unpopulate(val, "DaysAfterModificationGreaterThan", &d.DaysAfterModificationGreaterThan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeleteRetentionPolicy. +func (d DeleteRetentionPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowPermanentDelete", d.AllowPermanentDelete) + populate(objectMap, "days", d.Days) + populate(objectMap, "enabled", d.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeleteRetentionPolicy. +func (d *DeleteRetentionPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowPermanentDelete": + err = unpopulate(val, "AllowPermanentDelete", &d.AllowPermanentDelete) + delete(rawMsg, key) + case "days": + err = unpopulate(val, "Days", &d.Days) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &d.Enabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedAccount. +func (d DeletedAccount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedAccount. +func (d *DeletedAccount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedAccountListResult. +func (d DeletedAccountListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedAccountListResult. +func (d *DeletedAccountListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedAccountProperties. +func (d DeletedAccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "creationTime", d.CreationTime) + populate(objectMap, "deletionTime", d.DeletionTime) + populate(objectMap, "location", d.Location) + populate(objectMap, "restoreReference", d.RestoreReference) + populate(objectMap, "storageAccountResourceId", d.StorageAccountResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedAccountProperties. +func (d *DeletedAccountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationTime": + err = unpopulate(val, "CreationTime", &d.CreationTime) + delete(rawMsg, key) + case "deletionTime": + err = unpopulate(val, "DeletionTime", &d.DeletionTime) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "restoreReference": + err = unpopulate(val, "RestoreReference", &d.RestoreReference) + delete(rawMsg, key) + case "storageAccountResourceId": + err = unpopulate(val, "StorageAccountResourceID", &d.StorageAccountResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedShare. +func (d DeletedShare) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deletedShareName", d.DeletedShareName) + populate(objectMap, "deletedShareVersion", d.DeletedShareVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedShare. +func (d *DeletedShare) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deletedShareName": + err = unpopulate(val, "DeletedShareName", &d.DeletedShareName) + delete(rawMsg, key) + case "deletedShareVersion": + err = unpopulate(val, "DeletedShareVersion", &d.DeletedShareVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Dimension. +func (d Dimension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Dimension. +func (d *Dimension) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Encryption. +func (e Encryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", e.EncryptionIdentity) + populate(objectMap, "keySource", e.KeySource) + populate(objectMap, "keyvaultproperties", e.KeyVaultProperties) + populate(objectMap, "requireInfrastructureEncryption", e.RequireInfrastructureEncryption) + populate(objectMap, "services", e.Services) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Encryption. +func (e *Encryption) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "EncryptionIdentity", &e.EncryptionIdentity) + delete(rawMsg, key) + case "keySource": + err = unpopulate(val, "KeySource", &e.KeySource) + delete(rawMsg, key) + case "keyvaultproperties": + err = unpopulate(val, "KeyVaultProperties", &e.KeyVaultProperties) + delete(rawMsg, key) + case "requireInfrastructureEncryption": + err = unpopulate(val, "RequireInfrastructureEncryption", &e.RequireInfrastructureEncryption) + delete(rawMsg, key) + case "services": + err = unpopulate(val, "Services", &e.Services) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionIdentity. +func (e EncryptionIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "federatedIdentityClientId", e.EncryptionFederatedIdentityClientID) + populate(objectMap, "userAssignedIdentity", e.EncryptionUserAssignedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionIdentity. +func (e *EncryptionIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "federatedIdentityClientId": + err = unpopulate(val, "EncryptionFederatedIdentityClientID", &e.EncryptionFederatedIdentityClientID) + delete(rawMsg, key) + case "userAssignedIdentity": + err = unpopulate(val, "EncryptionUserAssignedIdentity", &e.EncryptionUserAssignedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScope. +func (e EncryptionScope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", e.EncryptionScopeProperties) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScope. +func (e *EncryptionScope) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "EncryptionScopeProperties", &e.EncryptionScopeProperties) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScopeKeyVaultProperties. +func (e EncryptionScopeKeyVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentVersionedKeyIdentifier", e.CurrentVersionedKeyIdentifier) + populate(objectMap, "keyUri", e.KeyURI) + populateDateTimeRFC3339(objectMap, "lastKeyRotationTimestamp", e.LastKeyRotationTimestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScopeKeyVaultProperties. +func (e *EncryptionScopeKeyVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentVersionedKeyIdentifier": + err = unpopulate(val, "CurrentVersionedKeyIdentifier", &e.CurrentVersionedKeyIdentifier) + delete(rawMsg, key) + case "keyUri": + err = unpopulate(val, "KeyURI", &e.KeyURI) + delete(rawMsg, key) + case "lastKeyRotationTimestamp": + err = unpopulateDateTimeRFC3339(val, "LastKeyRotationTimestamp", &e.LastKeyRotationTimestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScopeListResult. +func (e EncryptionScopeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScopeListResult. +func (e *EncryptionScopeListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScopeProperties. +func (e EncryptionScopeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "creationTime", e.CreationTime) + populate(objectMap, "keyVaultProperties", e.KeyVaultProperties) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", e.LastModifiedTime) + populate(objectMap, "requireInfrastructureEncryption", e.RequireInfrastructureEncryption) + populate(objectMap, "source", e.Source) + populate(objectMap, "state", e.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScopeProperties. +func (e *EncryptionScopeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "creationTime": + err = unpopulateDateTimeRFC3339(val, "CreationTime", &e.CreationTime) + delete(rawMsg, key) + case "keyVaultProperties": + err = unpopulate(val, "KeyVaultProperties", &e.KeyVaultProperties) + delete(rawMsg, key) + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &e.LastModifiedTime) + delete(rawMsg, key) + case "requireInfrastructureEncryption": + err = unpopulate(val, "RequireInfrastructureEncryption", &e.RequireInfrastructureEncryption) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &e.Source) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &e.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionService. +func (e EncryptionService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", e.Enabled) + populate(objectMap, "keyType", e.KeyType) + populateDateTimeRFC3339(objectMap, "lastEnabledTime", e.LastEnabledTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionService. +func (e *EncryptionService) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &e.Enabled) + delete(rawMsg, key) + case "keyType": + err = unpopulate(val, "KeyType", &e.KeyType) + delete(rawMsg, key) + case "lastEnabledTime": + err = unpopulateDateTimeRFC3339(val, "LastEnabledTime", &e.LastEnabledTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionServices. +func (e EncryptionServices) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blob", e.Blob) + populate(objectMap, "file", e.File) + populate(objectMap, "queue", e.Queue) + populate(objectMap, "table", e.Table) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionServices. +func (e *EncryptionServices) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blob": + err = unpopulate(val, "Blob", &e.Blob) + delete(rawMsg, key) + case "file": + err = unpopulate(val, "File", &e.File) + delete(rawMsg, key) + case "queue": + err = unpopulate(val, "Queue", &e.Queue) + delete(rawMsg, key) + case "table": + err = unpopulate(val, "Table", &e.Table) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Endpoints. +func (e Endpoints) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blob", e.Blob) + populate(objectMap, "dfs", e.Dfs) + populate(objectMap, "file", e.File) + populate(objectMap, "internetEndpoints", e.InternetEndpoints) + populate(objectMap, "microsoftEndpoints", e.MicrosoftEndpoints) + populate(objectMap, "queue", e.Queue) + populate(objectMap, "table", e.Table) + populate(objectMap, "web", e.Web) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Endpoints. +func (e *Endpoints) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blob": + err = unpopulate(val, "Blob", &e.Blob) + delete(rawMsg, key) + case "dfs": + err = unpopulate(val, "Dfs", &e.Dfs) + delete(rawMsg, key) + case "file": + err = unpopulate(val, "File", &e.File) + delete(rawMsg, key) + case "internetEndpoints": + err = unpopulate(val, "InternetEndpoints", &e.InternetEndpoints) + delete(rawMsg, key) + case "microsoftEndpoints": + err = unpopulate(val, "MicrosoftEndpoints", &e.MicrosoftEndpoints) + delete(rawMsg, key) + case "queue": + err = unpopulate(val, "Queue", &e.Queue) + delete(rawMsg, key) + case "table": + err = unpopulate(val, "Table", &e.Table) + delete(rawMsg, key) + case "web": + err = unpopulate(val, "Web", &e.Web) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorAdditionalInfo. +func (e ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "info", e.Info) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorAdditionalInfo. +func (e *ErrorAdditionalInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "info": + err = unpopulate(val, "Info", &e.Info) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetail. +func (e *ErrorDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalInfo": + err = unpopulate(val, "AdditionalInfo", &e.AdditionalInfo) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponse. +func (e ErrorResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", e.Error) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponse. +func (e *ErrorResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "error": + err = unpopulate(val, "Error", &e.Error) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponseAutoGenerated. +func (e ErrorResponseAutoGenerated) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", e.Error) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseAutoGenerated. +func (e *ErrorResponseAutoGenerated) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "error": + err = unpopulate(val, "Error", &e.Error) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBody. +func (e ErrorResponseBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "message", e.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseBody. +func (e *ErrorResponseBody) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExtendedLocation. +func (e ExtendedLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtendedLocation. +func (e *ExtendedLocation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileServiceItems. +func (f FileServiceItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileServiceItems. +func (f *FileServiceItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileServiceProperties. +func (f FileServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", f.FileServiceProperties) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "sku", f.SKU) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileServiceProperties. +func (f *FileServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "FileServiceProperties", &f.FileServiceProperties) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &f.SKU) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileServicePropertiesProperties. +func (f FileServicePropertiesProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cors", f.Cors) + populate(objectMap, "protocolSettings", f.ProtocolSettings) + populate(objectMap, "shareDeleteRetentionPolicy", f.ShareDeleteRetentionPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileServicePropertiesProperties. +func (f *FileServicePropertiesProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cors": + err = unpopulate(val, "Cors", &f.Cors) + delete(rawMsg, key) + case "protocolSettings": + err = unpopulate(val, "ProtocolSettings", &f.ProtocolSettings) + delete(rawMsg, key) + case "shareDeleteRetentionPolicy": + err = unpopulate(val, "ShareDeleteRetentionPolicy", &f.ShareDeleteRetentionPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileShare. +func (f FileShare) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", f.Etag) + populate(objectMap, "properties", f.FileShareProperties) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileShare. +func (f *FileShare) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &f.Etag) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "FileShareProperties", &f.FileShareProperties) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileShareItem. +func (f FileShareItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", f.Etag) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileShareItem. +func (f *FileShareItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &f.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileShareItems. +func (f FileShareItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileShareItems. +func (f *FileShareItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileShareProperties. +func (f FileShareProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessTier", f.AccessTier) + populateDateTimeRFC3339(objectMap, "accessTierChangeTime", f.AccessTierChangeTime) + populate(objectMap, "accessTierStatus", f.AccessTierStatus) + populate(objectMap, "deleted", f.Deleted) + populateDateTimeRFC3339(objectMap, "deletedTime", f.DeletedTime) + populate(objectMap, "enabledProtocols", f.EnabledProtocols) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", f.LastModifiedTime) + populate(objectMap, "leaseDuration", f.LeaseDuration) + populate(objectMap, "leaseState", f.LeaseState) + populate(objectMap, "leaseStatus", f.LeaseStatus) + populate(objectMap, "metadata", f.Metadata) + populate(objectMap, "remainingRetentionDays", f.RemainingRetentionDays) + populate(objectMap, "rootSquash", f.RootSquash) + populate(objectMap, "shareQuota", f.ShareQuota) + populate(objectMap, "shareUsageBytes", f.ShareUsageBytes) + populate(objectMap, "signedIdentifiers", f.SignedIdentifiers) + populateDateTimeRFC3339(objectMap, "snapshotTime", f.SnapshotTime) + populate(objectMap, "version", f.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileShareProperties. +func (f *FileShareProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessTier": + err = unpopulate(val, "AccessTier", &f.AccessTier) + delete(rawMsg, key) + case "accessTierChangeTime": + err = unpopulateDateTimeRFC3339(val, "AccessTierChangeTime", &f.AccessTierChangeTime) + delete(rawMsg, key) + case "accessTierStatus": + err = unpopulate(val, "AccessTierStatus", &f.AccessTierStatus) + delete(rawMsg, key) + case "deleted": + err = unpopulate(val, "Deleted", &f.Deleted) + delete(rawMsg, key) + case "deletedTime": + err = unpopulateDateTimeRFC3339(val, "DeletedTime", &f.DeletedTime) + delete(rawMsg, key) + case "enabledProtocols": + err = unpopulate(val, "EnabledProtocols", &f.EnabledProtocols) + delete(rawMsg, key) + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &f.LastModifiedTime) + delete(rawMsg, key) + case "leaseDuration": + err = unpopulate(val, "LeaseDuration", &f.LeaseDuration) + delete(rawMsg, key) + case "leaseState": + err = unpopulate(val, "LeaseState", &f.LeaseState) + delete(rawMsg, key) + case "leaseStatus": + err = unpopulate(val, "LeaseStatus", &f.LeaseStatus) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &f.Metadata) + delete(rawMsg, key) + case "remainingRetentionDays": + err = unpopulate(val, "RemainingRetentionDays", &f.RemainingRetentionDays) + delete(rawMsg, key) + case "rootSquash": + err = unpopulate(val, "RootSquash", &f.RootSquash) + delete(rawMsg, key) + case "shareQuota": + err = unpopulate(val, "ShareQuota", &f.ShareQuota) + delete(rawMsg, key) + case "shareUsageBytes": + err = unpopulate(val, "ShareUsageBytes", &f.ShareUsageBytes) + delete(rawMsg, key) + case "signedIdentifiers": + err = unpopulate(val, "SignedIdentifiers", &f.SignedIdentifiers) + delete(rawMsg, key) + case "snapshotTime": + err = unpopulateDateTimeRFC3339(val, "SnapshotTime", &f.SnapshotTime) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &f.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GeoReplicationStats. +func (g GeoReplicationStats) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "canFailover", g.CanFailover) + populate(objectMap, "canPlannedFailover", g.CanPlannedFailover) + populateDateTimeRFC3339(objectMap, "lastSyncTime", g.LastSyncTime) + populate(objectMap, "postFailoverRedundancy", g.PostFailoverRedundancy) + populate(objectMap, "postPlannedFailoverRedundancy", g.PostPlannedFailoverRedundancy) + populate(objectMap, "status", g.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GeoReplicationStats. +func (g *GeoReplicationStats) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "canFailover": + err = unpopulate(val, "CanFailover", &g.CanFailover) + delete(rawMsg, key) + case "canPlannedFailover": + err = unpopulate(val, "CanPlannedFailover", &g.CanPlannedFailover) + delete(rawMsg, key) + case "lastSyncTime": + err = unpopulateDateTimeRFC3339(val, "LastSyncTime", &g.LastSyncTime) + delete(rawMsg, key) + case "postFailoverRedundancy": + err = unpopulate(val, "PostFailoverRedundancy", &g.PostFailoverRedundancy) + delete(rawMsg, key) + case "postPlannedFailoverRedundancy": + err = unpopulate(val, "PostPlannedFailoverRedundancy", &g.PostPlannedFailoverRedundancy) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &g.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IPRule. +func (i IPRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["action"] = "Allow" + populate(objectMap, "value", i.IPAddressOrRange) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPRule. +func (i *IPRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &i.Action) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "IPAddressOrRange", &i.IPAddressOrRange) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Identity. +func (i Identity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", i.PrincipalID) + populate(objectMap, "tenantId", i.TenantID) + populate(objectMap, "type", i.Type) + populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Identity. +func (i *Identity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &i.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &i.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &i.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImmutabilityPolicy. +func (i ImmutabilityPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "id", i.ID) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImmutabilityPolicy. +func (i *ImmutabilityPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &i.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &i.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImmutabilityPolicyProperties. +func (i ImmutabilityPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "updateHistory", i.UpdateHistory) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImmutabilityPolicyProperties. +func (i *ImmutabilityPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &i.Etag) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &i.Properties) + delete(rawMsg, key) + case "updateHistory": + err = unpopulate(val, "UpdateHistory", &i.UpdateHistory) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImmutabilityPolicyProperty. +func (i ImmutabilityPolicyProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowProtectedAppendWrites", i.AllowProtectedAppendWrites) + populate(objectMap, "allowProtectedAppendWritesAll", i.AllowProtectedAppendWritesAll) + populate(objectMap, "immutabilityPeriodSinceCreationInDays", i.ImmutabilityPeriodSinceCreationInDays) + populate(objectMap, "state", i.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImmutabilityPolicyProperty. +func (i *ImmutabilityPolicyProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowProtectedAppendWrites": + err = unpopulate(val, "AllowProtectedAppendWrites", &i.AllowProtectedAppendWrites) + delete(rawMsg, key) + case "allowProtectedAppendWritesAll": + err = unpopulate(val, "AllowProtectedAppendWritesAll", &i.AllowProtectedAppendWritesAll) + delete(rawMsg, key) + case "immutabilityPeriodSinceCreationInDays": + err = unpopulate(val, "ImmutabilityPeriodSinceCreationInDays", &i.ImmutabilityPeriodSinceCreationInDays) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &i.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImmutableStorageAccount. +func (i ImmutableStorageAccount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", i.Enabled) + populate(objectMap, "immutabilityPolicy", i.ImmutabilityPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImmutableStorageAccount. +func (i *ImmutableStorageAccount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &i.Enabled) + delete(rawMsg, key) + case "immutabilityPolicy": + err = unpopulate(val, "ImmutabilityPolicy", &i.ImmutabilityPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImmutableStorageWithVersioning. +func (i ImmutableStorageWithVersioning) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", i.Enabled) + populate(objectMap, "migrationState", i.MigrationState) + populateDateTimeRFC3339(objectMap, "timeStamp", i.TimeStamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImmutableStorageWithVersioning. +func (i *ImmutableStorageWithVersioning) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &i.Enabled) + delete(rawMsg, key) + case "migrationState": + err = unpopulate(val, "MigrationState", &i.MigrationState) + delete(rawMsg, key) + case "timeStamp": + err = unpopulateDateTimeRFC3339(val, "TimeStamp", &i.TimeStamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyCreationTime. +func (k KeyCreationTime) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "key1", k.Key1) + populateDateTimeRFC3339(objectMap, "key2", k.Key2) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyCreationTime. +func (k *KeyCreationTime) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "key1": + err = unpopulateDateTimeRFC3339(val, "Key1", &k.Key1) + delete(rawMsg, key) + case "key2": + err = unpopulateDateTimeRFC3339(val, "Key2", &k.Key2) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyPolicy. +func (k KeyPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyExpirationPeriodInDays", k.KeyExpirationPeriodInDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyPolicy. +func (k *KeyPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyExpirationPeriodInDays": + err = unpopulate(val, "KeyExpirationPeriodInDays", &k.KeyExpirationPeriodInDays) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVaultProperties. +func (k KeyVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "currentVersionedKeyExpirationTimestamp", k.CurrentVersionedKeyExpirationTimestamp) + populate(objectMap, "currentVersionedKeyIdentifier", k.CurrentVersionedKeyIdentifier) + populate(objectMap, "keyname", k.KeyName) + populate(objectMap, "keyvaulturi", k.KeyVaultURI) + populate(objectMap, "keyversion", k.KeyVersion) + populateDateTimeRFC3339(objectMap, "lastKeyRotationTimestamp", k.LastKeyRotationTimestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultProperties. +func (k *KeyVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentVersionedKeyExpirationTimestamp": + err = unpopulateDateTimeRFC3339(val, "CurrentVersionedKeyExpirationTimestamp", &k.CurrentVersionedKeyExpirationTimestamp) + delete(rawMsg, key) + case "currentVersionedKeyIdentifier": + err = unpopulate(val, "CurrentVersionedKeyIdentifier", &k.CurrentVersionedKeyIdentifier) + delete(rawMsg, key) + case "keyname": + err = unpopulate(val, "KeyName", &k.KeyName) + delete(rawMsg, key) + case "keyvaulturi": + err = unpopulate(val, "KeyVaultURI", &k.KeyVaultURI) + delete(rawMsg, key) + case "keyversion": + err = unpopulate(val, "KeyVersion", &k.KeyVersion) + delete(rawMsg, key) + case "lastKeyRotationTimestamp": + err = unpopulateDateTimeRFC3339(val, "LastKeyRotationTimestamp", &k.LastKeyRotationTimestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LastAccessTimeTrackingPolicy. +func (l LastAccessTimeTrackingPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobType", l.BlobType) + populate(objectMap, "enable", l.Enable) + populate(objectMap, "name", l.Name) + populate(objectMap, "trackingGranularityInDays", l.TrackingGranularityInDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LastAccessTimeTrackingPolicy. +func (l *LastAccessTimeTrackingPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blobType": + err = unpopulate(val, "BlobType", &l.BlobType) + delete(rawMsg, key) + case "enable": + err = unpopulate(val, "Enable", &l.Enable) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "trackingGranularityInDays": + err = unpopulate(val, "TrackingGranularityInDays", &l.TrackingGranularityInDays) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LeaseContainerRequest. +func (l LeaseContainerRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", l.Action) + populate(objectMap, "breakPeriod", l.BreakPeriod) + populate(objectMap, "leaseDuration", l.LeaseDuration) + populate(objectMap, "leaseId", l.LeaseID) + populate(objectMap, "proposedLeaseId", l.ProposedLeaseID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LeaseContainerRequest. +func (l *LeaseContainerRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &l.Action) + delete(rawMsg, key) + case "breakPeriod": + err = unpopulate(val, "BreakPeriod", &l.BreakPeriod) + delete(rawMsg, key) + case "leaseDuration": + err = unpopulate(val, "LeaseDuration", &l.LeaseDuration) + delete(rawMsg, key) + case "leaseId": + err = unpopulate(val, "LeaseID", &l.LeaseID) + delete(rawMsg, key) + case "proposedLeaseId": + err = unpopulate(val, "ProposedLeaseID", &l.ProposedLeaseID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LeaseContainerResponse. +func (l LeaseContainerResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "leaseId", l.LeaseID) + populate(objectMap, "leaseTimeSeconds", l.LeaseTimeSeconds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LeaseContainerResponse. +func (l *LeaseContainerResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "leaseId": + err = unpopulate(val, "LeaseID", &l.LeaseID) + delete(rawMsg, key) + case "leaseTimeSeconds": + err = unpopulate(val, "LeaseTimeSeconds", &l.LeaseTimeSeconds) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LeaseShareRequest. +func (l LeaseShareRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", l.Action) + populate(objectMap, "breakPeriod", l.BreakPeriod) + populate(objectMap, "leaseDuration", l.LeaseDuration) + populate(objectMap, "leaseId", l.LeaseID) + populate(objectMap, "proposedLeaseId", l.ProposedLeaseID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LeaseShareRequest. +func (l *LeaseShareRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &l.Action) + delete(rawMsg, key) + case "breakPeriod": + err = unpopulate(val, "BreakPeriod", &l.BreakPeriod) + delete(rawMsg, key) + case "leaseDuration": + err = unpopulate(val, "LeaseDuration", &l.LeaseDuration) + delete(rawMsg, key) + case "leaseId": + err = unpopulate(val, "LeaseID", &l.LeaseID) + delete(rawMsg, key) + case "proposedLeaseId": + err = unpopulate(val, "ProposedLeaseID", &l.ProposedLeaseID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LeaseShareResponse. +func (l LeaseShareResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "leaseId", l.LeaseID) + populate(objectMap, "leaseTimeSeconds", l.LeaseTimeSeconds) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LeaseShareResponse. +func (l *LeaseShareResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "leaseId": + err = unpopulate(val, "LeaseID", &l.LeaseID) + delete(rawMsg, key) + case "leaseTimeSeconds": + err = unpopulate(val, "LeaseTimeSeconds", &l.LeaseTimeSeconds) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LegalHold. +func (l LegalHold) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowProtectedAppendWritesAll", l.AllowProtectedAppendWritesAll) + populate(objectMap, "hasLegalHold", l.HasLegalHold) + populate(objectMap, "tags", l.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LegalHold. +func (l *LegalHold) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowProtectedAppendWritesAll": + err = unpopulate(val, "AllowProtectedAppendWritesAll", &l.AllowProtectedAppendWritesAll) + delete(rawMsg, key) + case "hasLegalHold": + err = unpopulate(val, "HasLegalHold", &l.HasLegalHold) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &l.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LegalHoldProperties. +func (l LegalHoldProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hasLegalHold", l.HasLegalHold) + populate(objectMap, "protectedAppendWritesHistory", l.ProtectedAppendWritesHistory) + populate(objectMap, "tags", l.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LegalHoldProperties. +func (l *LegalHoldProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "hasLegalHold": + err = unpopulate(val, "HasLegalHold", &l.HasLegalHold) + delete(rawMsg, key) + case "protectedAppendWritesHistory": + err = unpopulate(val, "ProtectedAppendWritesHistory", &l.ProtectedAppendWritesHistory) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &l.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListAccountSasResponse. +func (l ListAccountSasResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountSasToken", l.AccountSasToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListAccountSasResponse. +func (l *ListAccountSasResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accountSasToken": + err = unpopulate(val, "AccountSasToken", &l.AccountSasToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListBlobInventoryPolicy. +func (l ListBlobInventoryPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListBlobInventoryPolicy. +func (l *ListBlobInventoryPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListContainerItem. +func (l ListContainerItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", l.Etag) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListContainerItem. +func (l *ListContainerItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &l.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListContainerItems. +func (l ListContainerItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListContainerItems. +func (l *ListContainerItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListQueue. +func (l ListQueue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.QueueProperties) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListQueue. +func (l *ListQueue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "QueueProperties", &l.QueueProperties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListQueueProperties. +func (l ListQueueProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "metadata", l.Metadata) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListQueueProperties. +func (l *ListQueueProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "metadata": + err = unpopulate(val, "Metadata", &l.Metadata) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListQueueResource. +func (l ListQueueResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListQueueResource. +func (l *ListQueueResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListQueueServices. +func (l ListQueueServices) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListQueueServices. +func (l *ListQueueServices) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListServiceSasResponse. +func (l ListServiceSasResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceSasToken", l.ServiceSasToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListServiceSasResponse. +func (l *ListServiceSasResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "serviceSasToken": + err = unpopulate(val, "ServiceSasToken", &l.ServiceSasToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListTableResource. +func (l ListTableResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListTableResource. +func (l *ListTableResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListTableServices. +func (l ListTableServices) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListTableServices. +func (l *ListTableServices) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocalUser. +func (l LocalUser) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalUser. +func (l *LocalUser) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocalUserKeys. +func (l LocalUserKeys) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sshAuthorizedKeys", l.SSHAuthorizedKeys) + populate(objectMap, "sharedKey", l.SharedKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalUserKeys. +func (l *LocalUserKeys) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sshAuthorizedKeys": + err = unpopulate(val, "SSHAuthorizedKeys", &l.SSHAuthorizedKeys) + delete(rawMsg, key) + case "sharedKey": + err = unpopulate(val, "SharedKey", &l.SharedKey) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocalUserProperties. +func (l LocalUserProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hasSshKey", l.HasSSHKey) + populate(objectMap, "hasSshPassword", l.HasSSHPassword) + populate(objectMap, "hasSharedKey", l.HasSharedKey) + populate(objectMap, "homeDirectory", l.HomeDirectory) + populate(objectMap, "permissionScopes", l.PermissionScopes) + populate(objectMap, "sshAuthorizedKeys", l.SSHAuthorizedKeys) + populate(objectMap, "sid", l.Sid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalUserProperties. +func (l *LocalUserProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "hasSshKey": + err = unpopulate(val, "HasSSHKey", &l.HasSSHKey) + delete(rawMsg, key) + case "hasSshPassword": + err = unpopulate(val, "HasSSHPassword", &l.HasSSHPassword) + delete(rawMsg, key) + case "hasSharedKey": + err = unpopulate(val, "HasSharedKey", &l.HasSharedKey) + delete(rawMsg, key) + case "homeDirectory": + err = unpopulate(val, "HomeDirectory", &l.HomeDirectory) + delete(rawMsg, key) + case "permissionScopes": + err = unpopulate(val, "PermissionScopes", &l.PermissionScopes) + delete(rawMsg, key) + case "sshAuthorizedKeys": + err = unpopulate(val, "SSHAuthorizedKeys", &l.SSHAuthorizedKeys) + delete(rawMsg, key) + case "sid": + err = unpopulate(val, "Sid", &l.Sid) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocalUserRegeneratePasswordResult. +func (l LocalUserRegeneratePasswordResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sshPassword", l.SSHPassword) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalUserRegeneratePasswordResult. +func (l *LocalUserRegeneratePasswordResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sshPassword": + err = unpopulate(val, "SSHPassword", &l.SSHPassword) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocalUsers. +func (l LocalUsers) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocalUsers. +func (l *LocalUsers) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicy. +func (m ManagementPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicy. +func (m *ManagementPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyAction. +func (m ManagementPolicyAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseBlob", m.BaseBlob) + populate(objectMap, "snapshot", m.Snapshot) + populate(objectMap, "version", m.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyAction. +func (m *ManagementPolicyAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseBlob": + err = unpopulate(val, "BaseBlob", &m.BaseBlob) + delete(rawMsg, key) + case "snapshot": + err = unpopulate(val, "Snapshot", &m.Snapshot) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &m.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyBaseBlob. +func (m ManagementPolicyBaseBlob) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "delete", m.Delete) + populate(objectMap, "enableAutoTierToHotFromCool", m.EnableAutoTierToHotFromCool) + populate(objectMap, "tierToArchive", m.TierToArchive) + populate(objectMap, "tierToCold", m.TierToCold) + populate(objectMap, "tierToCool", m.TierToCool) + populate(objectMap, "tierToHot", m.TierToHot) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyBaseBlob. +func (m *ManagementPolicyBaseBlob) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "delete": + err = unpopulate(val, "Delete", &m.Delete) + delete(rawMsg, key) + case "enableAutoTierToHotFromCool": + err = unpopulate(val, "EnableAutoTierToHotFromCool", &m.EnableAutoTierToHotFromCool) + delete(rawMsg, key) + case "tierToArchive": + err = unpopulate(val, "TierToArchive", &m.TierToArchive) + delete(rawMsg, key) + case "tierToCold": + err = unpopulate(val, "TierToCold", &m.TierToCold) + delete(rawMsg, key) + case "tierToCool": + err = unpopulate(val, "TierToCool", &m.TierToCool) + delete(rawMsg, key) + case "tierToHot": + err = unpopulate(val, "TierToHot", &m.TierToHot) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyDefinition. +func (m ManagementPolicyDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", m.Actions) + populate(objectMap, "filters", m.Filters) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyDefinition. +func (m *ManagementPolicyDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &m.Actions) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, "Filters", &m.Filters) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyFilter. +func (m ManagementPolicyFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blobIndexMatch", m.BlobIndexMatch) + populate(objectMap, "blobTypes", m.BlobTypes) + populate(objectMap, "prefixMatch", m.PrefixMatch) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyFilter. +func (m *ManagementPolicyFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blobIndexMatch": + err = unpopulate(val, "BlobIndexMatch", &m.BlobIndexMatch) + delete(rawMsg, key) + case "blobTypes": + err = unpopulate(val, "BlobTypes", &m.BlobTypes) + delete(rawMsg, key) + case "prefixMatch": + err = unpopulate(val, "PrefixMatch", &m.PrefixMatch) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyProperties. +func (m ManagementPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "lastModifiedTime", m.LastModifiedTime) + populate(objectMap, "policy", m.Policy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyProperties. +func (m *ManagementPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lastModifiedTime": + err = unpopulateDateTimeRFC3339(val, "LastModifiedTime", &m.LastModifiedTime) + delete(rawMsg, key) + case "policy": + err = unpopulate(val, "Policy", &m.Policy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyRule. +func (m ManagementPolicyRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "definition", m.Definition) + populate(objectMap, "enabled", m.Enabled) + populate(objectMap, "name", m.Name) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyRule. +func (m *ManagementPolicyRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "definition": + err = unpopulate(val, "Definition", &m.Definition) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &m.Enabled) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicySchema. +func (m ManagementPolicySchema) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "rules", m.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicySchema. +func (m *ManagementPolicySchema) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "rules": + err = unpopulate(val, "Rules", &m.Rules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicySnapShot. +func (m ManagementPolicySnapShot) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "delete", m.Delete) + populate(objectMap, "tierToArchive", m.TierToArchive) + populate(objectMap, "tierToCold", m.TierToCold) + populate(objectMap, "tierToCool", m.TierToCool) + populate(objectMap, "tierToHot", m.TierToHot) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicySnapShot. +func (m *ManagementPolicySnapShot) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "delete": + err = unpopulate(val, "Delete", &m.Delete) + delete(rawMsg, key) + case "tierToArchive": + err = unpopulate(val, "TierToArchive", &m.TierToArchive) + delete(rawMsg, key) + case "tierToCold": + err = unpopulate(val, "TierToCold", &m.TierToCold) + delete(rawMsg, key) + case "tierToCool": + err = unpopulate(val, "TierToCool", &m.TierToCool) + delete(rawMsg, key) + case "tierToHot": + err = unpopulate(val, "TierToHot", &m.TierToHot) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementPolicyVersion. +func (m ManagementPolicyVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "delete", m.Delete) + populate(objectMap, "tierToArchive", m.TierToArchive) + populate(objectMap, "tierToCold", m.TierToCold) + populate(objectMap, "tierToCool", m.TierToCool) + populate(objectMap, "tierToHot", m.TierToHot) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementPolicyVersion. +func (m *ManagementPolicyVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "delete": + err = unpopulate(val, "Delete", &m.Delete) + delete(rawMsg, key) + case "tierToArchive": + err = unpopulate(val, "TierToArchive", &m.TierToArchive) + delete(rawMsg, key) + case "tierToCold": + err = unpopulate(val, "TierToCold", &m.TierToCold) + delete(rawMsg, key) + case "tierToCool": + err = unpopulate(val, "TierToCool", &m.TierToCool) + delete(rawMsg, key) + case "tierToHot": + err = unpopulate(val, "TierToHot", &m.TierToHot) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetricSpecification. +func (m MetricSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationType", m.AggregationType) + populate(objectMap, "category", m.Category) + populate(objectMap, "dimensions", m.Dimensions) + populate(objectMap, "displayDescription", m.DisplayDescription) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "fillGapWithZero", m.FillGapWithZero) + populate(objectMap, "name", m.Name) + populate(objectMap, "resourceIdDimensionNameOverride", m.ResourceIDDimensionNameOverride) + populate(objectMap, "unit", m.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetricSpecification. +func (m *MetricSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aggregationType": + err = unpopulate(val, "AggregationType", &m.AggregationType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &m.Category) + delete(rawMsg, key) + case "dimensions": + err = unpopulate(val, "Dimensions", &m.Dimensions) + delete(rawMsg, key) + case "displayDescription": + err = unpopulate(val, "DisplayDescription", &m.DisplayDescription) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &m.DisplayName) + delete(rawMsg, key) + case "fillGapWithZero": + err = unpopulate(val, "FillGapWithZero", &m.FillGapWithZero) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "resourceIdDimensionNameOverride": + err = unpopulate(val, "ResourceIDDimensionNameOverride", &m.ResourceIDDimensionNameOverride) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &m.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Multichannel. +func (m Multichannel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", m.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Multichannel. +func (m *Multichannel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &m.Enabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkRuleSet. +func (n NetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypass", n.Bypass) + populate(objectMap, "defaultAction", n.DefaultAction) + populate(objectMap, "ipRules", n.IPRules) + populate(objectMap, "resourceAccessRules", n.ResourceAccessRules) + populate(objectMap, "virtualNetworkRules", n.VirtualNetworkRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkRuleSet. +func (n *NetworkRuleSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bypass": + err = unpopulate(val, "Bypass", &n.Bypass) + delete(rawMsg, key) + case "defaultAction": + err = unpopulate(val, "DefaultAction", &n.DefaultAction) + delete(rawMsg, key) + case "ipRules": + err = unpopulate(val, "IPRules", &n.IPRules) + delete(rawMsg, key) + case "resourceAccessRules": + err = unpopulate(val, "ResourceAccessRules", &n.ResourceAccessRules) + delete(rawMsg, key) + case "virtualNetworkRules": + err = unpopulate(val, "VirtualNetworkRules", &n.VirtualNetworkRules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ObjectReplicationPolicies. +func (o ObjectReplicationPolicies) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ObjectReplicationPolicies. +func (o *ObjectReplicationPolicies) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ObjectReplicationPolicy. +func (o ObjectReplicationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ObjectReplicationPolicy. +func (o *ObjectReplicationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ObjectReplicationPolicyFilter. +func (o ObjectReplicationPolicyFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "minCreationTime", o.MinCreationTime) + populate(objectMap, "prefixMatch", o.PrefixMatch) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ObjectReplicationPolicyFilter. +func (o *ObjectReplicationPolicyFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "minCreationTime": + err = unpopulate(val, "MinCreationTime", &o.MinCreationTime) + delete(rawMsg, key) + case "prefixMatch": + err = unpopulate(val, "PrefixMatch", &o.PrefixMatch) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ObjectReplicationPolicyProperties. +func (o ObjectReplicationPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationAccount", o.DestinationAccount) + populateDateTimeRFC3339(objectMap, "enabledTime", o.EnabledTime) + populate(objectMap, "policyId", o.PolicyID) + populate(objectMap, "rules", o.Rules) + populate(objectMap, "sourceAccount", o.SourceAccount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ObjectReplicationPolicyProperties. +func (o *ObjectReplicationPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "destinationAccount": + err = unpopulate(val, "DestinationAccount", &o.DestinationAccount) + delete(rawMsg, key) + case "enabledTime": + err = unpopulateDateTimeRFC3339(val, "EnabledTime", &o.EnabledTime) + delete(rawMsg, key) + case "policyId": + err = unpopulate(val, "PolicyID", &o.PolicyID) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &o.Rules) + delete(rawMsg, key) + case "sourceAccount": + err = unpopulate(val, "SourceAccount", &o.SourceAccount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ObjectReplicationPolicyRule. +func (o ObjectReplicationPolicyRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationContainer", o.DestinationContainer) + populate(objectMap, "filters", o.Filters) + populate(objectMap, "ruleId", o.RuleID) + populate(objectMap, "sourceContainer", o.SourceContainer) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ObjectReplicationPolicyRule. +func (o *ObjectReplicationPolicyRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "destinationContainer": + err = unpopulate(val, "DestinationContainer", &o.DestinationContainer) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, "Filters", &o.Filters) + delete(rawMsg, key) + case "ruleId": + err = unpopulate(val, "RuleID", &o.RuleID) + delete(rawMsg, key) + case "sourceContainer": + err = unpopulate(val, "SourceContainer", &o.SourceContainer) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "display", o.Display) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.OperationProperties) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "OperationProperties", &o.OperationProperties) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationProperties. +func (o OperationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceSpecification", o.ServiceSpecification) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationProperties. +func (o *OperationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "serviceSpecification": + err = unpopulate(val, "ServiceSpecification", &o.ServiceSpecification) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PermissionScope. +func (p PermissionScope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "permissions", p.Permissions) + populate(objectMap, "resourceName", p.ResourceName) + populate(objectMap, "service", p.Service) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PermissionScope. +func (p *PermissionScope) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "permissions": + err = unpopulate(val, "Permissions", &p.Permissions) + delete(rawMsg, key) + case "resourceName": + err = unpopulate(val, "ResourceName", &p.ResourceName) + delete(rawMsg, key) + case "service": + err = unpopulate(val, "Service", &p.Service) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpoint. +func (p *PrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnection. +func (p *PrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionListResult. +func (p *PrivateEndpointConnectionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionProperties. +func (p *PrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResource. +func (p *PrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceListResult. +func (p *PrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceProperties. +func (p *PrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupId": + err = unpopulate(val, "GroupID", &p.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &p.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &p.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionState. +func (p PrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionRequired", p.ActionRequired) + populate(objectMap, "description", p.Description) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionState. +func (p *PrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionRequired": + err = unpopulate(val, "ActionRequired", &p.ActionRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProtectedAppendWritesHistory. +func (p ProtectedAppendWritesHistory) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowProtectedAppendWritesAll", p.AllowProtectedAppendWritesAll) + populateDateTimeRFC3339(objectMap, "timestamp", p.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProtectedAppendWritesHistory. +func (p *ProtectedAppendWritesHistory) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowProtectedAppendWritesAll": + err = unpopulate(val, "AllowProtectedAppendWritesAll", &p.AllowProtectedAppendWritesAll) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &p.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProtocolSettings. +func (p ProtocolSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "smb", p.Smb) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProtocolSettings. +func (p *ProtocolSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "smb": + err = unpopulate(val, "Smb", &p.Smb) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProxyResource. +func (p ProxyResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProxyResource. +func (p *ProxyResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Queue. +func (q Queue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", q.ID) + populate(objectMap, "name", q.Name) + populate(objectMap, "properties", q.QueueProperties) + populate(objectMap, "type", q.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Queue. +func (q *Queue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &q.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &q.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "QueueProperties", &q.QueueProperties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &q.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QueueProperties. +func (q QueueProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "approximateMessageCount", q.ApproximateMessageCount) + populate(objectMap, "metadata", q.Metadata) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueueProperties. +func (q *QueueProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "approximateMessageCount": + err = unpopulate(val, "ApproximateMessageCount", &q.ApproximateMessageCount) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &q.Metadata) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QueueServiceProperties. +func (q QueueServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", q.ID) + populate(objectMap, "name", q.Name) + populate(objectMap, "properties", q.QueueServiceProperties) + populate(objectMap, "type", q.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueueServiceProperties. +func (q *QueueServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &q.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &q.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "QueueServiceProperties", &q.QueueServiceProperties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &q.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QueueServicePropertiesProperties. +func (q QueueServicePropertiesProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cors", q.Cors) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QueueServicePropertiesProperties. +func (q *QueueServicePropertiesProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cors": + err = unpopulate(val, "Cors", &q.Cors) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. +func (r *Resource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceAccessRule. +func (r ResourceAccessRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "tenantId", r.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceAccessRule. +func (r *ResourceAccessRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &r.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestorePolicyProperties. +func (r RestorePolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "days", r.Days) + populate(objectMap, "enabled", r.Enabled) + populateDateTimeRFC3339(objectMap, "lastEnabledTime", r.LastEnabledTime) + populateDateTimeRFC3339(objectMap, "minRestoreTime", r.MinRestoreTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestorePolicyProperties. +func (r *RestorePolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "days": + err = unpopulate(val, "Days", &r.Days) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &r.Enabled) + delete(rawMsg, key) + case "lastEnabledTime": + err = unpopulateDateTimeRFC3339(val, "LastEnabledTime", &r.LastEnabledTime) + delete(rawMsg, key) + case "minRestoreTime": + err = unpopulateDateTimeRFC3339(val, "MinRestoreTime", &r.MinRestoreTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Restriction. +func (r Restriction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reasonCode", r.ReasonCode) + populate(objectMap, "type", r.Type) + populate(objectMap, "values", r.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Restriction. +func (r *Restriction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "reasonCode": + err = unpopulate(val, "ReasonCode", &r.ReasonCode) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &r.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RoutingPreference. +func (r RoutingPreference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publishInternetEndpoints", r.PublishInternetEndpoints) + populate(objectMap, "publishMicrosoftEndpoints", r.PublishMicrosoftEndpoints) + populate(objectMap, "routingChoice", r.RoutingChoice) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoutingPreference. +func (r *RoutingPreference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "publishInternetEndpoints": + err = unpopulate(val, "PublishInternetEndpoints", &r.PublishInternetEndpoints) + delete(rawMsg, key) + case "publishMicrosoftEndpoints": + err = unpopulate(val, "PublishMicrosoftEndpoints", &r.PublishMicrosoftEndpoints) + delete(rawMsg, key) + case "routingChoice": + err = unpopulate(val, "RoutingChoice", &r.RoutingChoice) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUCapability. +func (s SKUCapability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUCapability. +func (s *SKUCapability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUInformation. +func (s SKUInformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capabilities", s.Capabilities) + populate(objectMap, "kind", s.Kind) + populate(objectMap, "locations", s.Locations) + populate(objectMap, "name", s.Name) + populate(objectMap, "resourceType", s.ResourceType) + populate(objectMap, "restrictions", s.Restrictions) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUInformation. +func (s *SKUInformation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capabilities": + err = unpopulate(val, "Capabilities", &s.Capabilities) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "locations": + err = unpopulate(val, "Locations", &s.Locations) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &s.ResourceType) + delete(rawMsg, key) + case "restrictions": + err = unpopulate(val, "Restrictions", &s.Restrictions) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUListResult. +func (s SKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUListResult. +func (s *SKUListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SSHPublicKey. +func (s SSHPublicKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "key", s.Key) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHPublicKey. +func (s *SSHPublicKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &s.Key) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SasPolicy. +func (s SasPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "expirationAction", s.ExpirationAction) + populate(objectMap, "sasExpirationPeriod", s.SasExpirationPeriod) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SasPolicy. +func (s *SasPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expirationAction": + err = unpopulate(val, "ExpirationAction", &s.ExpirationAction) + delete(rawMsg, key) + case "sasExpirationPeriod": + err = unpopulate(val, "SasExpirationPeriod", &s.SasExpirationPeriod) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceSasParameters. +func (s ServiceSasParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "rscc", s.CacheControl) + populate(objectMap, "canonicalizedResource", s.CanonicalizedResource) + populate(objectMap, "rscd", s.ContentDisposition) + populate(objectMap, "rsce", s.ContentEncoding) + populate(objectMap, "rscl", s.ContentLanguage) + populate(objectMap, "rsct", s.ContentType) + populate(objectMap, "signedIp", s.IPAddressOrRange) + populate(objectMap, "signedIdentifier", s.Identifier) + populate(objectMap, "keyToSign", s.KeyToSign) + populate(objectMap, "endPk", s.PartitionKeyEnd) + populate(objectMap, "startPk", s.PartitionKeyStart) + populate(objectMap, "signedPermission", s.Permissions) + populate(objectMap, "signedProtocol", s.Protocols) + populate(objectMap, "signedResource", s.Resource) + populate(objectMap, "endRk", s.RowKeyEnd) + populate(objectMap, "startRk", s.RowKeyStart) + populateDateTimeRFC3339(objectMap, "signedExpiry", s.SharedAccessExpiryTime) + populateDateTimeRFC3339(objectMap, "signedStart", s.SharedAccessStartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceSasParameters. +func (s *ServiceSasParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "rscc": + err = unpopulate(val, "CacheControl", &s.CacheControl) + delete(rawMsg, key) + case "canonicalizedResource": + err = unpopulate(val, "CanonicalizedResource", &s.CanonicalizedResource) + delete(rawMsg, key) + case "rscd": + err = unpopulate(val, "ContentDisposition", &s.ContentDisposition) + delete(rawMsg, key) + case "rsce": + err = unpopulate(val, "ContentEncoding", &s.ContentEncoding) + delete(rawMsg, key) + case "rscl": + err = unpopulate(val, "ContentLanguage", &s.ContentLanguage) + delete(rawMsg, key) + case "rsct": + err = unpopulate(val, "ContentType", &s.ContentType) + delete(rawMsg, key) + case "signedIp": + err = unpopulate(val, "IPAddressOrRange", &s.IPAddressOrRange) + delete(rawMsg, key) + case "signedIdentifier": + err = unpopulate(val, "Identifier", &s.Identifier) + delete(rawMsg, key) + case "keyToSign": + err = unpopulate(val, "KeyToSign", &s.KeyToSign) + delete(rawMsg, key) + case "endPk": + err = unpopulate(val, "PartitionKeyEnd", &s.PartitionKeyEnd) + delete(rawMsg, key) + case "startPk": + err = unpopulate(val, "PartitionKeyStart", &s.PartitionKeyStart) + delete(rawMsg, key) + case "signedPermission": + err = unpopulate(val, "Permissions", &s.Permissions) + delete(rawMsg, key) + case "signedProtocol": + err = unpopulate(val, "Protocols", &s.Protocols) + delete(rawMsg, key) + case "signedResource": + err = unpopulate(val, "Resource", &s.Resource) + delete(rawMsg, key) + case "endRk": + err = unpopulate(val, "RowKeyEnd", &s.RowKeyEnd) + delete(rawMsg, key) + case "startRk": + err = unpopulate(val, "RowKeyStart", &s.RowKeyStart) + delete(rawMsg, key) + case "signedExpiry": + err = unpopulateDateTimeRFC3339(val, "SharedAccessExpiryTime", &s.SharedAccessExpiryTime) + delete(rawMsg, key) + case "signedStart": + err = unpopulateDateTimeRFC3339(val, "SharedAccessStartTime", &s.SharedAccessStartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceSpecification. +func (s ServiceSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "metricSpecifications", s.MetricSpecifications) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceSpecification. +func (s *ServiceSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "metricSpecifications": + err = unpopulate(val, "MetricSpecifications", &s.MetricSpecifications) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SignedIdentifier. +func (s SignedIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessPolicy", s.AccessPolicy) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignedIdentifier. +func (s *SignedIdentifier) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessPolicy": + err = unpopulate(val, "AccessPolicy", &s.AccessPolicy) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SmbSetting. +func (s SmbSetting) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationMethods", s.AuthenticationMethods) + populate(objectMap, "channelEncryption", s.ChannelEncryption) + populate(objectMap, "kerberosTicketEncryption", s.KerberosTicketEncryption) + populate(objectMap, "multichannel", s.Multichannel) + populate(objectMap, "versions", s.Versions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SmbSetting. +func (s *SmbSetting) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authenticationMethods": + err = unpopulate(val, "AuthenticationMethods", &s.AuthenticationMethods) + delete(rawMsg, key) + case "channelEncryption": + err = unpopulate(val, "ChannelEncryption", &s.ChannelEncryption) + delete(rawMsg, key) + case "kerberosTicketEncryption": + err = unpopulate(val, "KerberosTicketEncryption", &s.KerberosTicketEncryption) + delete(rawMsg, key) + case "multichannel": + err = unpopulate(val, "Multichannel", &s.Multichannel) + delete(rawMsg, key) + case "versions": + err = unpopulate(val, "Versions", &s.Versions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateDateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateDateTimeRFC3339(val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateDateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Table. +func (t Table) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.TableProperties) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Table. +func (t *Table) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "TableProperties", &t.TableProperties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TableAccessPolicy. +func (t TableAccessPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expiryTime", t.ExpiryTime) + populate(objectMap, "permission", t.Permission) + populateDateTimeRFC3339(objectMap, "startTime", t.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TableAccessPolicy. +func (t *TableAccessPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiryTime": + err = unpopulateDateTimeRFC3339(val, "ExpiryTime", &t.ExpiryTime) + delete(rawMsg, key) + case "permission": + err = unpopulate(val, "Permission", &t.Permission) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &t.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TableProperties. +func (t TableProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "signedIdentifiers", t.SignedIdentifiers) + populate(objectMap, "tableName", t.TableName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TableProperties. +func (t *TableProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "signedIdentifiers": + err = unpopulate(val, "SignedIdentifiers", &t.SignedIdentifiers) + delete(rawMsg, key) + case "tableName": + err = unpopulate(val, "TableName", &t.TableName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TableServiceProperties. +func (t TableServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.TableServiceProperties) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TableServiceProperties. +func (t *TableServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "TableServiceProperties", &t.TableServiceProperties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TableServicePropertiesProperties. +func (t TableServicePropertiesProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cors", t.Cors) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TableServicePropertiesProperties. +func (t *TableServicePropertiesProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cors": + err = unpopulate(val, "Cors", &t.Cors) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TableSignedIdentifier. +func (t TableSignedIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessPolicy", t.AccessPolicy) + populate(objectMap, "id", t.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TableSignedIdentifier. +func (t *TableSignedIdentifier) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessPolicy": + err = unpopulate(val, "AccessPolicy", &t.AccessPolicy) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TagFilter. +func (t TagFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", t.Name) + populate(objectMap, "op", t.Op) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TagFilter. +func (t *TagFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "op": + err = unpopulate(val, "Op", &t.Op) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TagProperty. +func (t TagProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "objectIdentifier", t.ObjectIdentifier) + populate(objectMap, "tag", t.Tag) + populate(objectMap, "tenantId", t.TenantID) + populateDateTimeRFC3339(objectMap, "timestamp", t.Timestamp) + populate(objectMap, "upn", t.Upn) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TagProperty. +func (t *TagProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "objectIdentifier": + err = unpopulate(val, "ObjectIdentifier", &t.ObjectIdentifier) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &t.Tag) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &t.TenantID) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &t.Timestamp) + delete(rawMsg, key) + case "upn": + err = unpopulate(val, "Upn", &t.Upn) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedResource. +func (t TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "location", t.Location) + populate(objectMap, "name", t.Name) + populate(objectMap, "tags", t.Tags) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrackedResource. +func (t *TrackedResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateHistoryProperty. +func (u UpdateHistoryProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowProtectedAppendWrites", u.AllowProtectedAppendWrites) + populate(objectMap, "allowProtectedAppendWritesAll", u.AllowProtectedAppendWritesAll) + populate(objectMap, "immutabilityPeriodSinceCreationInDays", u.ImmutabilityPeriodSinceCreationInDays) + populate(objectMap, "objectIdentifier", u.ObjectIdentifier) + populate(objectMap, "tenantId", u.TenantID) + populateDateTimeRFC3339(objectMap, "timestamp", u.Timestamp) + populate(objectMap, "update", u.Update) + populate(objectMap, "upn", u.Upn) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateHistoryProperty. +func (u *UpdateHistoryProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowProtectedAppendWrites": + err = unpopulate(val, "AllowProtectedAppendWrites", &u.AllowProtectedAppendWrites) + delete(rawMsg, key) + case "allowProtectedAppendWritesAll": + err = unpopulate(val, "AllowProtectedAppendWritesAll", &u.AllowProtectedAppendWritesAll) + delete(rawMsg, key) + case "immutabilityPeriodSinceCreationInDays": + err = unpopulate(val, "ImmutabilityPeriodSinceCreationInDays", &u.ImmutabilityPeriodSinceCreationInDays) + delete(rawMsg, key) + case "objectIdentifier": + err = unpopulate(val, "ObjectIdentifier", &u.ObjectIdentifier) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &u.TenantID) + delete(rawMsg, key) + case "timestamp": + err = unpopulateDateTimeRFC3339(val, "Timestamp", &u.Timestamp) + delete(rawMsg, key) + case "update": + err = unpopulate(val, "Update", &u.Update) + delete(rawMsg, key) + case "upn": + err = unpopulate(val, "Upn", &u.Upn) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Usage. +func (u Usage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentValue", u.CurrentValue) + populate(objectMap, "limit", u.Limit) + populate(objectMap, "name", u.Name) + populate(objectMap, "unit", u.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Usage. +func (u *Usage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentValue": + err = unpopulate(val, "CurrentValue", &u.CurrentValue) + delete(rawMsg, key) + case "limit": + err = unpopulate(val, "Limit", &u.Limit) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &u.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UsageListResult. +func (u UsageListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UsageListResult. +func (u *UsageListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &u.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UsageName. +func (u UsageName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "localizedValue", u.LocalizedValue) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UsageName. +func (u *UsageName) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "localizedValue": + err = unpopulate(val, "LocalizedValue", &u.LocalizedValue) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &u.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkRule. +func (v VirtualNetworkRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["action"] = "Allow" + populate(objectMap, "state", v.State) + populate(objectMap, "id", v.VirtualNetworkResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkRule. +func (v *VirtualNetworkRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &v.Action) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &v.State) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "VirtualNetworkResourceID", &v.VirtualNetworkResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/objectreplicationpolicies_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/objectreplicationpolicies_client.go new file mode 100644 index 0000000000..dc91e8ca35 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/objectreplicationpolicies_client.go @@ -0,0 +1,324 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ObjectReplicationPoliciesClient contains the methods for the ObjectReplicationPolicies group. +// Don't use this type directly, use NewObjectReplicationPoliciesClient() instead. +type ObjectReplicationPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewObjectReplicationPoliciesClient creates a new instance of ObjectReplicationPoliciesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewObjectReplicationPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ObjectReplicationPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ObjectReplicationPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update the object replication policy of the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - objectReplicationPolicyID - For the destination account, provide the value 'default'. Configure the policy on the destination +// account first. For the source account, provide the value of the policy ID that is returned when you +// download the policy that was defined on the destination account. The policy is downloaded as a JSON file. +// - properties - The object replication policy set to a storage account. A unique policy ID will be created if absent. +// - options - ObjectReplicationPoliciesClientCreateOrUpdateOptions contains the optional parameters for the ObjectReplicationPoliciesClient.CreateOrUpdate +// method. +func (client *ObjectReplicationPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, properties ObjectReplicationPolicy, options *ObjectReplicationPoliciesClientCreateOrUpdateOptions) (ObjectReplicationPoliciesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ObjectReplicationPoliciesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, objectReplicationPolicyID, properties, options) + if err != nil { + return ObjectReplicationPoliciesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ObjectReplicationPoliciesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ObjectReplicationPoliciesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ObjectReplicationPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, properties ObjectReplicationPolicy, options *ObjectReplicationPoliciesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/objectReplicationPolicies/{objectReplicationPolicyId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if objectReplicationPolicyID == "" { + return nil, errors.New("parameter objectReplicationPolicyID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{objectReplicationPolicyId}", url.PathEscape(objectReplicationPolicyID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ObjectReplicationPoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (ObjectReplicationPoliciesClientCreateOrUpdateResponse, error) { + result := ObjectReplicationPoliciesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ObjectReplicationPolicy); err != nil { + return ObjectReplicationPoliciesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the object replication policy associated with the specified storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - objectReplicationPolicyID - For the destination account, provide the value 'default'. Configure the policy on the destination +// account first. For the source account, provide the value of the policy ID that is returned when you +// download the policy that was defined on the destination account. The policy is downloaded as a JSON file. +// - options - ObjectReplicationPoliciesClientDeleteOptions contains the optional parameters for the ObjectReplicationPoliciesClient.Delete +// method. +func (client *ObjectReplicationPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, options *ObjectReplicationPoliciesClientDeleteOptions) (ObjectReplicationPoliciesClientDeleteResponse, error) { + var err error + const operationName = "ObjectReplicationPoliciesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, objectReplicationPolicyID, options) + if err != nil { + return ObjectReplicationPoliciesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ObjectReplicationPoliciesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ObjectReplicationPoliciesClientDeleteResponse{}, err + } + return ObjectReplicationPoliciesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ObjectReplicationPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, options *ObjectReplicationPoliciesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/objectReplicationPolicies/{objectReplicationPolicyId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if objectReplicationPolicyID == "" { + return nil, errors.New("parameter objectReplicationPolicyID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{objectReplicationPolicyId}", url.PathEscape(objectReplicationPolicyID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get the object replication policy of the storage account by policy ID. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - objectReplicationPolicyID - For the destination account, provide the value 'default'. Configure the policy on the destination +// account first. For the source account, provide the value of the policy ID that is returned when you +// download the policy that was defined on the destination account. The policy is downloaded as a JSON file. +// - options - ObjectReplicationPoliciesClientGetOptions contains the optional parameters for the ObjectReplicationPoliciesClient.Get +// method. +func (client *ObjectReplicationPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, options *ObjectReplicationPoliciesClientGetOptions) (ObjectReplicationPoliciesClientGetResponse, error) { + var err error + const operationName = "ObjectReplicationPoliciesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, objectReplicationPolicyID, options) + if err != nil { + return ObjectReplicationPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ObjectReplicationPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ObjectReplicationPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ObjectReplicationPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, objectReplicationPolicyID string, options *ObjectReplicationPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/objectReplicationPolicies/{objectReplicationPolicyId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if objectReplicationPolicyID == "" { + return nil, errors.New("parameter objectReplicationPolicyID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{objectReplicationPolicyId}", url.PathEscape(objectReplicationPolicyID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ObjectReplicationPoliciesClient) getHandleResponse(resp *http.Response) (ObjectReplicationPoliciesClientGetResponse, error) { + result := ObjectReplicationPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ObjectReplicationPolicy); err != nil { + return ObjectReplicationPoliciesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List the object replication policies associated with the storage account. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - ObjectReplicationPoliciesClientListOptions contains the optional parameters for the ObjectReplicationPoliciesClient.NewListPager +// method. +func (client *ObjectReplicationPoliciesClient) NewListPager(resourceGroupName string, accountName string, options *ObjectReplicationPoliciesClientListOptions) *runtime.Pager[ObjectReplicationPoliciesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ObjectReplicationPoliciesClientListResponse]{ + More: func(page ObjectReplicationPoliciesClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *ObjectReplicationPoliciesClientListResponse) (ObjectReplicationPoliciesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ObjectReplicationPoliciesClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return ObjectReplicationPoliciesClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ObjectReplicationPoliciesClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ObjectReplicationPoliciesClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ObjectReplicationPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *ObjectReplicationPoliciesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/objectReplicationPolicies" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ObjectReplicationPoliciesClient) listHandleResponse(resp *http.Response) (ObjectReplicationPoliciesClientListResponse, error) { + result := ObjectReplicationPoliciesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ObjectReplicationPolicies); err != nil { + return ObjectReplicationPoliciesClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/operations_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/operations_client.go new file mode 100644 index 0000000000..74621df131 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/operations_client.go @@ -0,0 +1,89 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - Lists all of the available Storage Rest API operations. +// +// Generated from API version 2023-01-01 +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return OperationsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OperationsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OperationsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Storage/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/options.go new file mode 100644 index 0000000000..d143bdb48b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/options.go @@ -0,0 +1,577 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +// AccountsClientBeginAbortHierarchicalNamespaceMigrationOptions contains the optional parameters for the AccountsClient.BeginAbortHierarchicalNamespaceMigration +// method. +type AccountsClientBeginAbortHierarchicalNamespaceMigrationOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AccountsClientBeginCreateOptions contains the optional parameters for the AccountsClient.BeginCreate method. +type AccountsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AccountsClientBeginCustomerInitiatedMigrationOptions contains the optional parameters for the AccountsClient.BeginCustomerInitiatedMigration +// method. +type AccountsClientBeginCustomerInitiatedMigrationOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AccountsClientBeginFailoverOptions contains the optional parameters for the AccountsClient.BeginFailover method. +type AccountsClientBeginFailoverOptions struct { + // The parameter is set to 'Planned' to indicate whether a Planned failover is requested.. Specifying any value will set the + // value to Planned. + FailoverType *string + + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AccountsClientBeginHierarchicalNamespaceMigrationOptions contains the optional parameters for the AccountsClient.BeginHierarchicalNamespaceMigration +// method. +type AccountsClientBeginHierarchicalNamespaceMigrationOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AccountsClientBeginRestoreBlobRangesOptions contains the optional parameters for the AccountsClient.BeginRestoreBlobRanges +// method. +type AccountsClientBeginRestoreBlobRangesOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// AccountsClientCheckNameAvailabilityOptions contains the optional parameters for the AccountsClient.CheckNameAvailability +// method. +type AccountsClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientDeleteOptions contains the optional parameters for the AccountsClient.Delete method. +type AccountsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientGetCustomerInitiatedMigrationOptions contains the optional parameters for the AccountsClient.GetCustomerInitiatedMigration +// method. +type AccountsClientGetCustomerInitiatedMigrationOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientGetPropertiesOptions contains the optional parameters for the AccountsClient.GetProperties method. +type AccountsClientGetPropertiesOptions struct { + // May be used to expand the properties within account's properties. By default, data is not included when fetching properties. + // Currently we only support geoReplicationStats and blobRestoreStatus. + Expand *StorageAccountExpand +} + +// AccountsClientListAccountSASOptions contains the optional parameters for the AccountsClient.ListAccountSAS method. +type AccountsClientListAccountSASOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListByResourceGroupOptions contains the optional parameters for the AccountsClient.NewListByResourceGroupPager +// method. +type AccountsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListKeysOptions contains the optional parameters for the AccountsClient.ListKeys method. +type AccountsClientListKeysOptions struct { + // Specifies type of the key to be listed. Possible value is kerb.. Specifying any value will set the value to kerb. + Expand *string +} + +// AccountsClientListOptions contains the optional parameters for the AccountsClient.NewListPager method. +type AccountsClientListOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListServiceSASOptions contains the optional parameters for the AccountsClient.ListServiceSAS method. +type AccountsClientListServiceSASOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientRegenerateKeyOptions contains the optional parameters for the AccountsClient.RegenerateKey method. +type AccountsClientRegenerateKeyOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientRevokeUserDelegationKeysOptions contains the optional parameters for the AccountsClient.RevokeUserDelegationKeys +// method. +type AccountsClientRevokeUserDelegationKeysOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientUpdateOptions contains the optional parameters for the AccountsClient.Update method. +type AccountsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientBeginObjectLevelWormOptions contains the optional parameters for the BlobContainersClient.BeginObjectLevelWorm +// method. +type BlobContainersClientBeginObjectLevelWormOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// BlobContainersClientClearLegalHoldOptions contains the optional parameters for the BlobContainersClient.ClearLegalHold +// method. +type BlobContainersClientClearLegalHoldOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientCreateOptions contains the optional parameters for the BlobContainersClient.Create method. +type BlobContainersClientCreateOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientCreateOrUpdateImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.CreateOrUpdateImmutabilityPolicy +// method. +type BlobContainersClientCreateOrUpdateImmutabilityPolicyOptions struct { + // The entity state (ETag) version of the immutability policy to update. A value of "*" can be used to apply the operation + // only if the immutability policy already exists. If omitted, this operation will + // always be applied. + IfMatch *string + + // The ImmutabilityPolicy Properties that will be created or updated to a blob container. + Parameters *ImmutabilityPolicy +} + +// BlobContainersClientDeleteImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.DeleteImmutabilityPolicy +// method. +type BlobContainersClientDeleteImmutabilityPolicyOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientDeleteOptions contains the optional parameters for the BlobContainersClient.Delete method. +type BlobContainersClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientExtendImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.ExtendImmutabilityPolicy +// method. +type BlobContainersClientExtendImmutabilityPolicyOptions struct { + // The ImmutabilityPolicy Properties that will be extended for a blob container. + Parameters *ImmutabilityPolicy +} + +// BlobContainersClientGetImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.GetImmutabilityPolicy +// method. +type BlobContainersClientGetImmutabilityPolicyOptions struct { + // The entity state (ETag) version of the immutability policy to update. A value of "*" can be used to apply the operation + // only if the immutability policy already exists. If omitted, this operation will + // always be applied. + IfMatch *string +} + +// BlobContainersClientGetOptions contains the optional parameters for the BlobContainersClient.Get method. +type BlobContainersClientGetOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientLeaseOptions contains the optional parameters for the BlobContainersClient.Lease method. +type BlobContainersClientLeaseOptions struct { + // Lease Container request body. + Parameters *LeaseContainerRequest +} + +// BlobContainersClientListOptions contains the optional parameters for the BlobContainersClient.NewListPager method. +type BlobContainersClientListOptions struct { + // Optional. When specified, only container names starting with the filter will be listed. + Filter *string + + // Optional, used to include the properties for soft deleted blob containers. + Include *ListContainersInclude + + // Optional. Specified maximum number of containers that can be included in the list. + Maxpagesize *string +} + +// BlobContainersClientLockImmutabilityPolicyOptions contains the optional parameters for the BlobContainersClient.LockImmutabilityPolicy +// method. +type BlobContainersClientLockImmutabilityPolicyOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientSetLegalHoldOptions contains the optional parameters for the BlobContainersClient.SetLegalHold method. +type BlobContainersClientSetLegalHoldOptions struct { + // placeholder for future optional parameters +} + +// BlobContainersClientUpdateOptions contains the optional parameters for the BlobContainersClient.Update method. +type BlobContainersClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// BlobInventoryPoliciesClientCreateOrUpdateOptions contains the optional parameters for the BlobInventoryPoliciesClient.CreateOrUpdate +// method. +type BlobInventoryPoliciesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// BlobInventoryPoliciesClientDeleteOptions contains the optional parameters for the BlobInventoryPoliciesClient.Delete method. +type BlobInventoryPoliciesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// BlobInventoryPoliciesClientGetOptions contains the optional parameters for the BlobInventoryPoliciesClient.Get method. +type BlobInventoryPoliciesClientGetOptions struct { + // placeholder for future optional parameters +} + +// BlobInventoryPoliciesClientListOptions contains the optional parameters for the BlobInventoryPoliciesClient.NewListPager +// method. +type BlobInventoryPoliciesClientListOptions struct { + // placeholder for future optional parameters +} + +// BlobServicesClientGetServicePropertiesOptions contains the optional parameters for the BlobServicesClient.GetServiceProperties +// method. +type BlobServicesClientGetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// BlobServicesClientListOptions contains the optional parameters for the BlobServicesClient.NewListPager method. +type BlobServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// BlobServicesClientSetServicePropertiesOptions contains the optional parameters for the BlobServicesClient.SetServiceProperties +// method. +type BlobServicesClientSetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsClientGetOptions contains the optional parameters for the DeletedAccountsClient.Get method. +type DeletedAccountsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsClientListOptions contains the optional parameters for the DeletedAccountsClient.NewListPager method. +type DeletedAccountsClientListOptions struct { + // placeholder for future optional parameters +} + +// EncryptionScopesClientGetOptions contains the optional parameters for the EncryptionScopesClient.Get method. +type EncryptionScopesClientGetOptions struct { + // placeholder for future optional parameters +} + +// EncryptionScopesClientListOptions contains the optional parameters for the EncryptionScopesClient.NewListPager method. +type EncryptionScopesClientListOptions struct { + // Optional. When specified, only encryption scope names starting with the filter will be listed. + Filter *string + + // Optional, when specified, will list encryption scopes with the specific state. Defaults to All + Include *ListEncryptionScopesInclude + + // Optional, specifies the maximum number of encryption scopes that will be included in the list response. + Maxpagesize *int32 +} + +// EncryptionScopesClientPatchOptions contains the optional parameters for the EncryptionScopesClient.Patch method. +type EncryptionScopesClientPatchOptions struct { + // placeholder for future optional parameters +} + +// EncryptionScopesClientPutOptions contains the optional parameters for the EncryptionScopesClient.Put method. +type EncryptionScopesClientPutOptions struct { + // placeholder for future optional parameters +} + +// FileServicesClientGetServicePropertiesOptions contains the optional parameters for the FileServicesClient.GetServiceProperties +// method. +type FileServicesClientGetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// FileServicesClientListOptions contains the optional parameters for the FileServicesClient.List method. +type FileServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// FileServicesClientSetServicePropertiesOptions contains the optional parameters for the FileServicesClient.SetServiceProperties +// method. +type FileServicesClientSetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// FileSharesClientCreateOptions contains the optional parameters for the FileSharesClient.Create method. +type FileSharesClientCreateOptions struct { + // Optional, used to expand the properties within share's properties. Valid values are: snapshots. Should be passed as a string + // with delimiter ',' + Expand *string +} + +// FileSharesClientDeleteOptions contains the optional parameters for the FileSharesClient.Delete method. +type FileSharesClientDeleteOptions struct { + // Optional. Valid values are: snapshots, leased-snapshots, none. The default value is snapshots. For 'snapshots', the file + // share is deleted including all of its file share snapshots. If the file share + // contains leased-snapshots, the deletion fails. For 'leased-snapshots', the file share is deleted included all of its file + // share snapshots (leased/unleased). For 'none', the file share is deleted if it + // has no share snapshots. If the file share contains any snapshots (leased or unleased), the deletion fails. + Include *string + + // Optional, used to delete a snapshot. + XMSSnapshot *string +} + +// FileSharesClientGetOptions contains the optional parameters for the FileSharesClient.Get method. +type FileSharesClientGetOptions struct { + // Optional, used to expand the properties within share's properties. Valid values are: stats. Should be passed as a string + // with delimiter ','. + Expand *string + + // Optional, used to retrieve properties of a snapshot. + XMSSnapshot *string +} + +// FileSharesClientLeaseOptions contains the optional parameters for the FileSharesClient.Lease method. +type FileSharesClientLeaseOptions struct { + // Lease Share request body. + Parameters *LeaseShareRequest + + // Optional. Specify the snapshot time to lease a snapshot. + XMSSnapshot *string +} + +// FileSharesClientListOptions contains the optional parameters for the FileSharesClient.NewListPager method. +type FileSharesClientListOptions struct { + // Optional, used to expand the properties within share's properties. Valid values are: deleted, snapshots. Should be passed + // as a string with delimiter ',' + Expand *string + + // Optional. When specified, only share names starting with the filter will be listed. + Filter *string + + // Optional. Specified maximum number of shares that can be included in the list. + Maxpagesize *string +} + +// FileSharesClientRestoreOptions contains the optional parameters for the FileSharesClient.Restore method. +type FileSharesClientRestoreOptions struct { + // placeholder for future optional parameters +} + +// FileSharesClientUpdateOptions contains the optional parameters for the FileSharesClient.Update method. +type FileSharesClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// LocalUsersClientCreateOrUpdateOptions contains the optional parameters for the LocalUsersClient.CreateOrUpdate method. +type LocalUsersClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// LocalUsersClientDeleteOptions contains the optional parameters for the LocalUsersClient.Delete method. +type LocalUsersClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// LocalUsersClientGetOptions contains the optional parameters for the LocalUsersClient.Get method. +type LocalUsersClientGetOptions struct { + // placeholder for future optional parameters +} + +// LocalUsersClientListKeysOptions contains the optional parameters for the LocalUsersClient.ListKeys method. +type LocalUsersClientListKeysOptions struct { + // placeholder for future optional parameters +} + +// LocalUsersClientListOptions contains the optional parameters for the LocalUsersClient.NewListPager method. +type LocalUsersClientListOptions struct { + // placeholder for future optional parameters +} + +// LocalUsersClientRegeneratePasswordOptions contains the optional parameters for the LocalUsersClient.RegeneratePassword +// method. +type LocalUsersClientRegeneratePasswordOptions struct { + // placeholder for future optional parameters +} + +// ManagementPoliciesClientCreateOrUpdateOptions contains the optional parameters for the ManagementPoliciesClient.CreateOrUpdate +// method. +type ManagementPoliciesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ManagementPoliciesClientDeleteOptions contains the optional parameters for the ManagementPoliciesClient.Delete method. +type ManagementPoliciesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ManagementPoliciesClientGetOptions contains the optional parameters for the ManagementPoliciesClient.Get method. +type ManagementPoliciesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ObjectReplicationPoliciesClientCreateOrUpdateOptions contains the optional parameters for the ObjectReplicationPoliciesClient.CreateOrUpdate +// method. +type ObjectReplicationPoliciesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ObjectReplicationPoliciesClientDeleteOptions contains the optional parameters for the ObjectReplicationPoliciesClient.Delete +// method. +type ObjectReplicationPoliciesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ObjectReplicationPoliciesClientGetOptions contains the optional parameters for the ObjectReplicationPoliciesClient.Get +// method. +type ObjectReplicationPoliciesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ObjectReplicationPoliciesClientListOptions contains the optional parameters for the ObjectReplicationPoliciesClient.NewListPager +// method. +type ObjectReplicationPoliciesClientListOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Delete +// method. +type PrivateEndpointConnectionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +type PrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListPager +// method. +type PrivateEndpointConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientPutOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Put +// method. +type PrivateEndpointConnectionsClientPutOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesClientListByStorageAccountOptions contains the optional parameters for the PrivateLinkResourcesClient.ListByStorageAccount +// method. +type PrivateLinkResourcesClientListByStorageAccountOptions struct { + // placeholder for future optional parameters +} + +// QueueClientCreateOptions contains the optional parameters for the QueueClient.Create method. +type QueueClientCreateOptions struct { + // placeholder for future optional parameters +} + +// QueueClientDeleteOptions contains the optional parameters for the QueueClient.Delete method. +type QueueClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// QueueClientGetOptions contains the optional parameters for the QueueClient.Get method. +type QueueClientGetOptions struct { + // placeholder for future optional parameters +} + +// QueueClientListOptions contains the optional parameters for the QueueClient.NewListPager method. +type QueueClientListOptions struct { + // Optional, When specified, only the queues with a name starting with the given filter will be listed. + Filter *string + + // Optional, a maximum number of queues that should be included in a list queue response + Maxpagesize *string +} + +// QueueClientUpdateOptions contains the optional parameters for the QueueClient.Update method. +type QueueClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// QueueServicesClientGetServicePropertiesOptions contains the optional parameters for the QueueServicesClient.GetServiceProperties +// method. +type QueueServicesClientGetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// QueueServicesClientListOptions contains the optional parameters for the QueueServicesClient.List method. +type QueueServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// QueueServicesClientSetServicePropertiesOptions contains the optional parameters for the QueueServicesClient.SetServiceProperties +// method. +type QueueServicesClientSetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// SKUsClientListOptions contains the optional parameters for the SKUsClient.NewListPager method. +type SKUsClientListOptions struct { + // placeholder for future optional parameters +} + +// TableClientCreateOptions contains the optional parameters for the TableClient.Create method. +type TableClientCreateOptions struct { + // The parameters to provide to create a table. + Parameters *Table +} + +// TableClientDeleteOptions contains the optional parameters for the TableClient.Delete method. +type TableClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// TableClientGetOptions contains the optional parameters for the TableClient.Get method. +type TableClientGetOptions struct { + // placeholder for future optional parameters +} + +// TableClientListOptions contains the optional parameters for the TableClient.NewListPager method. +type TableClientListOptions struct { + // placeholder for future optional parameters +} + +// TableClientUpdateOptions contains the optional parameters for the TableClient.Update method. +type TableClientUpdateOptions struct { + // The parameters to provide to create a table. + Parameters *Table +} + +// TableServicesClientGetServicePropertiesOptions contains the optional parameters for the TableServicesClient.GetServiceProperties +// method. +type TableServicesClientGetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// TableServicesClientListOptions contains the optional parameters for the TableServicesClient.List method. +type TableServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// TableServicesClientSetServicePropertiesOptions contains the optional parameters for the TableServicesClient.SetServiceProperties +// method. +type TableServicesClientSetServicePropertiesOptions struct { + // placeholder for future optional parameters +} + +// UsagesClientListByLocationOptions contains the optional parameters for the UsagesClient.NewListByLocationPager method. +type UsagesClientListByLocationOptions struct { + // placeholder for future optional parameters +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privateendpointconnections_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privateendpointconnections_client.go new file mode 100644 index 0000000000..cde0f2d21d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privateendpointconnections_client.go @@ -0,0 +1,318 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Delete - Deletes the specified private endpoint connection associated with the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Azure resource +// - options - PrivateEndpointConnectionsClientDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Delete +// method. +func (client *PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientDeleteOptions) (PrivateEndpointConnectionsClientDeleteResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientDeleteResponse{}, err + } + return PrivateEndpointConnectionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the specified private endpoint connection associated with the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Azure resource +// - options - PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (PrivateEndpointConnectionsClientGetResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientGetResponse, error) { + result := PrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all the private endpoint connections associated with the storage account. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListPager +// method. +func (client *PrivateEndpointConnectionsClient) NewListPager(resourceGroupName string, accountName string, options *PrivateEndpointConnectionsClientListOptions) *runtime.Pager[PrivateEndpointConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointConnectionsClientListResponse]{ + More: func(page PrivateEndpointConnectionsClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointConnectionsClientListResponse) (PrivateEndpointConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateEndpointConnectionsClient.NewListPager") + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *PrivateEndpointConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateEndpointConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientListResponse, error) { + result := PrivateEndpointConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + return result, nil +} + +// Put - Update the state of specified private endpoint connection associated with the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Azure resource +// - properties - The private endpoint connection properties. +// - options - PrivateEndpointConnectionsClientPutOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Put +// method. +func (client *PrivateEndpointConnectionsClient) Put(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsClientPutOptions) (PrivateEndpointConnectionsClientPutResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, properties, options) + if err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *PrivateEndpointConnectionsClient) putCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *PrivateEndpointConnectionsClient) putHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientPutResponse, error) { + result := PrivateEndpointConnectionsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsClientPutResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privatelinkresources_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privatelinkresources_client.go new file mode 100644 index 0000000000..7127815f09 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/privatelinkresources_client.go @@ -0,0 +1,110 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +type PrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// ListByStorageAccount - Gets the private link resources that need to be created for a storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - PrivateLinkResourcesClientListByStorageAccountOptions contains the optional parameters for the PrivateLinkResourcesClient.ListByStorageAccount +// method. +func (client *PrivateLinkResourcesClient) ListByStorageAccount(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesClientListByStorageAccountOptions) (PrivateLinkResourcesClientListByStorageAccountResponse, error) { + var err error + const operationName = "PrivateLinkResourcesClient.ListByStorageAccount" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listByStorageAccountCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateLinkResourcesClientListByStorageAccountResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateLinkResourcesClientListByStorageAccountResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateLinkResourcesClientListByStorageAccountResponse{}, err + } + resp, err := client.listByStorageAccountHandleResponse(httpResp) + return resp, err +} + +// listByStorageAccountCreateRequest creates the ListByStorageAccount request. +func (client *PrivateLinkResourcesClient) listByStorageAccountCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesClientListByStorageAccountOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateLinkResources" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByStorageAccountHandleResponse handles the ListByStorageAccount response. +func (client *PrivateLinkResourcesClient) listByStorageAccountHandleResponse(resp *http.Response) (PrivateLinkResourcesClientListByStorageAccountResponse, error) { + result := PrivateLinkResourcesClientListByStorageAccountResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return PrivateLinkResourcesClientListByStorageAccountResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queue_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queue_client.go new file mode 100644 index 0000000000..743fcc983d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queue_client.go @@ -0,0 +1,401 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// QueueClient contains the methods for the Queue group. +// Don't use this type directly, use NewQueueClient() instead. +type QueueClient struct { + internal *arm.Client + subscriptionID string +} + +// NewQueueClient creates a new instance of QueueClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewQueueClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*QueueClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &QueueClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates a new queue with the specified queue name, under the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - queueName - A queue name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of lowercase alphanumeric and dash(-) characters only, it should begin and end with +// an alphanumeric character and it cannot have two consecutive dash(-) characters. +// - queue - Queue properties and metadata to be created with +// - options - QueueClientCreateOptions contains the optional parameters for the QueueClient.Create method. +func (client *QueueClient) Create(ctx context.Context, resourceGroupName string, accountName string, queueName string, queue Queue, options *QueueClientCreateOptions) (QueueClientCreateResponse, error) { + var err error + const operationName = "QueueClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, queueName, queue, options) + if err != nil { + return QueueClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueueClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *QueueClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, queueName string, queue Queue, options *QueueClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/default/queues/{queueName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if queueName == "" { + return nil, errors.New("parameter queueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{queueName}", url.PathEscape(queueName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, queue); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *QueueClient) createHandleResponse(resp *http.Response) (QueueClientCreateResponse, error) { + result := QueueClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Queue); err != nil { + return QueueClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the queue with the specified queue name, under the specified account if it exists. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - queueName - A queue name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of lowercase alphanumeric and dash(-) characters only, it should begin and end with +// an alphanumeric character and it cannot have two consecutive dash(-) characters. +// - options - QueueClientDeleteOptions contains the optional parameters for the QueueClient.Delete method. +func (client *QueueClient) Delete(ctx context.Context, resourceGroupName string, accountName string, queueName string, options *QueueClientDeleteOptions) (QueueClientDeleteResponse, error) { + var err error + const operationName = "QueueClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, queueName, options) + if err != nil { + return QueueClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return QueueClientDeleteResponse{}, err + } + return QueueClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *QueueClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, queueName string, options *QueueClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/default/queues/{queueName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if queueName == "" { + return nil, errors.New("parameter queueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{queueName}", url.PathEscape(queueName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the queue with the specified queue name, under the specified account if it exists. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - queueName - A queue name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of lowercase alphanumeric and dash(-) characters only, it should begin and end with +// an alphanumeric character and it cannot have two consecutive dash(-) characters. +// - options - QueueClientGetOptions contains the optional parameters for the QueueClient.Get method. +func (client *QueueClient) Get(ctx context.Context, resourceGroupName string, accountName string, queueName string, options *QueueClientGetOptions) (QueueClientGetResponse, error) { + var err error + const operationName = "QueueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, queueName, options) + if err != nil { + return QueueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *QueueClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, queueName string, options *QueueClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/default/queues/{queueName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if queueName == "" { + return nil, errors.New("parameter queueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{queueName}", url.PathEscape(queueName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *QueueClient) getHandleResponse(resp *http.Response) (QueueClientGetResponse, error) { + result := QueueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Queue); err != nil { + return QueueClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all the queues under the specified storage account +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - QueueClientListOptions contains the optional parameters for the QueueClient.NewListPager method. +func (client *QueueClient) NewListPager(resourceGroupName string, accountName string, options *QueueClientListOptions) *runtime.Pager[QueueClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[QueueClientListResponse]{ + More: func(page QueueClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *QueueClientListResponse) (QueueClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "QueueClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return QueueClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *QueueClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *QueueClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/default/queues" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + if options != nil && options.Maxpagesize != nil { + reqQP.Set("$maxpagesize", *options.Maxpagesize) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *QueueClient) listHandleResponse(resp *http.Response) (QueueClientListResponse, error) { + result := QueueClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListQueueResource); err != nil { + return QueueClientListResponse{}, err + } + return result, nil +} + +// Update - Creates a new queue with the specified queue name, under the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - queueName - A queue name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of lowercase alphanumeric and dash(-) characters only, it should begin and end with +// an alphanumeric character and it cannot have two consecutive dash(-) characters. +// - queue - Queue properties and metadata to be created with +// - options - QueueClientUpdateOptions contains the optional parameters for the QueueClient.Update method. +func (client *QueueClient) Update(ctx context.Context, resourceGroupName string, accountName string, queueName string, queue Queue, options *QueueClientUpdateOptions) (QueueClientUpdateResponse, error) { + var err error + const operationName = "QueueClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, queueName, queue, options) + if err != nil { + return QueueClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueueClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *QueueClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, queueName string, queue Queue, options *QueueClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/default/queues/{queueName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if queueName == "" { + return nil, errors.New("parameter queueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{queueName}", url.PathEscape(queueName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, queue); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *QueueClient) updateHandleResponse(resp *http.Response) (QueueClientUpdateResponse, error) { + result := QueueClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Queue); err != nil { + return QueueClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queueservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queueservices_client.go new file mode 100644 index 0000000000..75786fe949 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/queueservices_client.go @@ -0,0 +1,250 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// QueueServicesClient contains the methods for the QueueServices group. +// Don't use this type directly, use NewQueueServicesClient() instead. +type QueueServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewQueueServicesClient creates a new instance of QueueServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewQueueServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*QueueServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &QueueServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetServiceProperties - Gets the properties of a storage account’s Queue service, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - QueueServicesClientGetServicePropertiesOptions contains the optional parameters for the QueueServicesClient.GetServiceProperties +// method. +func (client *QueueServicesClient) GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, options *QueueServicesClientGetServicePropertiesOptions) (QueueServicesClientGetServicePropertiesResponse, error) { + var err error + const operationName = "QueueServicesClient.GetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return QueueServicesClientGetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueServicesClientGetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueueServicesClientGetServicePropertiesResponse{}, err + } + resp, err := client.getServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// getServicePropertiesCreateRequest creates the GetServiceProperties request. +func (client *QueueServicesClient) getServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *QueueServicesClientGetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/{queueServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{queueServiceName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getServicePropertiesHandleResponse handles the GetServiceProperties response. +func (client *QueueServicesClient) getServicePropertiesHandleResponse(resp *http.Response) (QueueServicesClientGetServicePropertiesResponse, error) { + result := QueueServicesClientGetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QueueServiceProperties); err != nil { + return QueueServicesClientGetServicePropertiesResponse{}, err + } + return result, nil +} + +// List - List all queue services for the storage account +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - QueueServicesClientListOptions contains the optional parameters for the QueueServicesClient.List method. +func (client *QueueServicesClient) List(ctx context.Context, resourceGroupName string, accountName string, options *QueueServicesClientListOptions) (QueueServicesClientListResponse, error) { + var err error + const operationName = "QueueServicesClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return QueueServicesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueServicesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueueServicesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *QueueServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *QueueServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *QueueServicesClient) listHandleResponse(resp *http.Response) (QueueServicesClientListResponse, error) { + result := QueueServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListQueueServices); err != nil { + return QueueServicesClientListResponse{}, err + } + return result, nil +} + +// SetServiceProperties - Sets the properties of a storage account’s Queue service, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The properties of a storage account’s Queue service, only properties for Storage Analytics and CORS (Cross-Origin +// Resource Sharing) rules can be specified. +// - options - QueueServicesClientSetServicePropertiesOptions contains the optional parameters for the QueueServicesClient.SetServiceProperties +// method. +func (client *QueueServicesClient) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters QueueServiceProperties, options *QueueServicesClientSetServicePropertiesOptions) (QueueServicesClientSetServicePropertiesResponse, error) { + var err error + const operationName = "QueueServicesClient.SetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return QueueServicesClientSetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueueServicesClientSetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueueServicesClientSetServicePropertiesResponse{}, err + } + resp, err := client.setServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// setServicePropertiesCreateRequest creates the SetServiceProperties request. +func (client *QueueServicesClient) setServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters QueueServiceProperties, options *QueueServicesClientSetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/queueServices/{queueServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{queueServiceName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// setServicePropertiesHandleResponse handles the SetServiceProperties response. +func (client *QueueServicesClient) setServicePropertiesHandleResponse(resp *http.Response) (QueueServicesClientSetServicePropertiesResponse, error) { + result := QueueServicesClientSetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QueueServiceProperties); err != nil { + return QueueServicesClientSetServicePropertiesResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/response_types.go new file mode 100644 index 0000000000..e5b7eb742c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/response_types.go @@ -0,0 +1,557 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +// AccountsClientAbortHierarchicalNamespaceMigrationResponse contains the response from method AccountsClient.BeginAbortHierarchicalNamespaceMigration. +type AccountsClientAbortHierarchicalNamespaceMigrationResponse struct { + // placeholder for future response values +} + +// AccountsClientCheckNameAvailabilityResponse contains the response from method AccountsClient.CheckNameAvailability. +type AccountsClientCheckNameAvailabilityResponse struct { + // The CheckNameAvailability operation response. + CheckNameAvailabilityResult +} + +// AccountsClientCreateResponse contains the response from method AccountsClient.BeginCreate. +type AccountsClientCreateResponse struct { + // The storage account. + Account +} + +// AccountsClientCustomerInitiatedMigrationResponse contains the response from method AccountsClient.BeginCustomerInitiatedMigration. +type AccountsClientCustomerInitiatedMigrationResponse struct { + // placeholder for future response values +} + +// AccountsClientDeleteResponse contains the response from method AccountsClient.Delete. +type AccountsClientDeleteResponse struct { + // placeholder for future response values +} + +// AccountsClientFailoverResponse contains the response from method AccountsClient.BeginFailover. +type AccountsClientFailoverResponse struct { + // placeholder for future response values +} + +// AccountsClientGetCustomerInitiatedMigrationResponse contains the response from method AccountsClient.GetCustomerInitiatedMigration. +type AccountsClientGetCustomerInitiatedMigrationResponse struct { + // The parameters or status associated with an ongoing or enqueued storage account migration in order to update its current + // SKU or region. + AccountMigration +} + +// AccountsClientGetPropertiesResponse contains the response from method AccountsClient.GetProperties. +type AccountsClientGetPropertiesResponse struct { + // The storage account. + Account +} + +// AccountsClientHierarchicalNamespaceMigrationResponse contains the response from method AccountsClient.BeginHierarchicalNamespaceMigration. +type AccountsClientHierarchicalNamespaceMigrationResponse struct { + // placeholder for future response values +} + +// AccountsClientListAccountSASResponse contains the response from method AccountsClient.ListAccountSAS. +type AccountsClientListAccountSASResponse struct { + // The List SAS credentials operation response. + ListAccountSasResponse +} + +// AccountsClientListByResourceGroupResponse contains the response from method AccountsClient.NewListByResourceGroupPager. +type AccountsClientListByResourceGroupResponse struct { + // The response from the List Storage Accounts operation. + AccountListResult +} + +// AccountsClientListKeysResponse contains the response from method AccountsClient.ListKeys. +type AccountsClientListKeysResponse struct { + // The response from the ListKeys operation. + AccountListKeysResult +} + +// AccountsClientListResponse contains the response from method AccountsClient.NewListPager. +type AccountsClientListResponse struct { + // The response from the List Storage Accounts operation. + AccountListResult +} + +// AccountsClientListServiceSASResponse contains the response from method AccountsClient.ListServiceSAS. +type AccountsClientListServiceSASResponse struct { + // The List service SAS credentials operation response. + ListServiceSasResponse +} + +// AccountsClientRegenerateKeyResponse contains the response from method AccountsClient.RegenerateKey. +type AccountsClientRegenerateKeyResponse struct { + // The response from the ListKeys operation. + AccountListKeysResult +} + +// AccountsClientRestoreBlobRangesResponse contains the response from method AccountsClient.BeginRestoreBlobRanges. +type AccountsClientRestoreBlobRangesResponse struct { + // Blob restore status. + BlobRestoreStatus +} + +// AccountsClientRevokeUserDelegationKeysResponse contains the response from method AccountsClient.RevokeUserDelegationKeys. +type AccountsClientRevokeUserDelegationKeysResponse struct { + // placeholder for future response values +} + +// AccountsClientUpdateResponse contains the response from method AccountsClient.Update. +type AccountsClientUpdateResponse struct { + // The storage account. + Account +} + +// BlobContainersClientClearLegalHoldResponse contains the response from method BlobContainersClient.ClearLegalHold. +type BlobContainersClientClearLegalHoldResponse struct { + // The LegalHold property of a blob container. + LegalHold +} + +// BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse contains the response from method BlobContainersClient.CreateOrUpdateImmutabilityPolicy. +type BlobContainersClientCreateOrUpdateImmutabilityPolicyResponse struct { + // The ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. + ImmutabilityPolicy + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// BlobContainersClientCreateResponse contains the response from method BlobContainersClient.Create. +type BlobContainersClientCreateResponse struct { + // Properties of the blob container, including Id, resource name, resource type, Etag. + BlobContainer +} + +// BlobContainersClientDeleteImmutabilityPolicyResponse contains the response from method BlobContainersClient.DeleteImmutabilityPolicy. +type BlobContainersClientDeleteImmutabilityPolicyResponse struct { + // The ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. + ImmutabilityPolicy + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// BlobContainersClientDeleteResponse contains the response from method BlobContainersClient.Delete. +type BlobContainersClientDeleteResponse struct { + // placeholder for future response values +} + +// BlobContainersClientExtendImmutabilityPolicyResponse contains the response from method BlobContainersClient.ExtendImmutabilityPolicy. +type BlobContainersClientExtendImmutabilityPolicyResponse struct { + // The ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. + ImmutabilityPolicy + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// BlobContainersClientGetImmutabilityPolicyResponse contains the response from method BlobContainersClient.GetImmutabilityPolicy. +type BlobContainersClientGetImmutabilityPolicyResponse struct { + // The ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. + ImmutabilityPolicy + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// BlobContainersClientGetResponse contains the response from method BlobContainersClient.Get. +type BlobContainersClientGetResponse struct { + // Properties of the blob container, including Id, resource name, resource type, Etag. + BlobContainer +} + +// BlobContainersClientLeaseResponse contains the response from method BlobContainersClient.Lease. +type BlobContainersClientLeaseResponse struct { + // Lease Container response schema. + LeaseContainerResponse +} + +// BlobContainersClientListResponse contains the response from method BlobContainersClient.NewListPager. +type BlobContainersClientListResponse struct { + // Response schema. Contains list of blobs returned, and if paging is requested or required, a URL to next page of containers. + ListContainerItems +} + +// BlobContainersClientLockImmutabilityPolicyResponse contains the response from method BlobContainersClient.LockImmutabilityPolicy. +type BlobContainersClientLockImmutabilityPolicyResponse struct { + // The ImmutabilityPolicy property of a blob container, including Id, resource name, resource type, Etag. + ImmutabilityPolicy + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// BlobContainersClientObjectLevelWormResponse contains the response from method BlobContainersClient.BeginObjectLevelWorm. +type BlobContainersClientObjectLevelWormResponse struct { + // placeholder for future response values +} + +// BlobContainersClientSetLegalHoldResponse contains the response from method BlobContainersClient.SetLegalHold. +type BlobContainersClientSetLegalHoldResponse struct { + // The LegalHold property of a blob container. + LegalHold +} + +// BlobContainersClientUpdateResponse contains the response from method BlobContainersClient.Update. +type BlobContainersClientUpdateResponse struct { + // Properties of the blob container, including Id, resource name, resource type, Etag. + BlobContainer +} + +// BlobInventoryPoliciesClientCreateOrUpdateResponse contains the response from method BlobInventoryPoliciesClient.CreateOrUpdate. +type BlobInventoryPoliciesClientCreateOrUpdateResponse struct { + // The storage account blob inventory policy. + BlobInventoryPolicy +} + +// BlobInventoryPoliciesClientDeleteResponse contains the response from method BlobInventoryPoliciesClient.Delete. +type BlobInventoryPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// BlobInventoryPoliciesClientGetResponse contains the response from method BlobInventoryPoliciesClient.Get. +type BlobInventoryPoliciesClientGetResponse struct { + // The storage account blob inventory policy. + BlobInventoryPolicy +} + +// BlobInventoryPoliciesClientListResponse contains the response from method BlobInventoryPoliciesClient.NewListPager. +type BlobInventoryPoliciesClientListResponse struct { + // List of blob inventory policies returned. + ListBlobInventoryPolicy +} + +// BlobServicesClientGetServicePropertiesResponse contains the response from method BlobServicesClient.GetServiceProperties. +type BlobServicesClientGetServicePropertiesResponse struct { + // The properties of a storage account’s Blob service. + BlobServiceProperties +} + +// BlobServicesClientListResponse contains the response from method BlobServicesClient.NewListPager. +type BlobServicesClientListResponse struct { + BlobServiceItems +} + +// BlobServicesClientSetServicePropertiesResponse contains the response from method BlobServicesClient.SetServiceProperties. +type BlobServicesClientSetServicePropertiesResponse struct { + // The properties of a storage account’s Blob service. + BlobServiceProperties +} + +// DeletedAccountsClientGetResponse contains the response from method DeletedAccountsClient.Get. +type DeletedAccountsClientGetResponse struct { + // Deleted storage account + DeletedAccount +} + +// DeletedAccountsClientListResponse contains the response from method DeletedAccountsClient.NewListPager. +type DeletedAccountsClientListResponse struct { + // The response from the List Deleted Accounts operation. + DeletedAccountListResult +} + +// EncryptionScopesClientGetResponse contains the response from method EncryptionScopesClient.Get. +type EncryptionScopesClientGetResponse struct { + // The Encryption Scope resource. + EncryptionScope +} + +// EncryptionScopesClientListResponse contains the response from method EncryptionScopesClient.NewListPager. +type EncryptionScopesClientListResponse struct { + // List of encryption scopes requested, and if paging is required, a URL to the next page of encryption scopes. + EncryptionScopeListResult +} + +// EncryptionScopesClientPatchResponse contains the response from method EncryptionScopesClient.Patch. +type EncryptionScopesClientPatchResponse struct { + // The Encryption Scope resource. + EncryptionScope +} + +// EncryptionScopesClientPutResponse contains the response from method EncryptionScopesClient.Put. +type EncryptionScopesClientPutResponse struct { + // The Encryption Scope resource. + EncryptionScope +} + +// FileServicesClientGetServicePropertiesResponse contains the response from method FileServicesClient.GetServiceProperties. +type FileServicesClientGetServicePropertiesResponse struct { + // The properties of File services in storage account. + FileServiceProperties +} + +// FileServicesClientListResponse contains the response from method FileServicesClient.List. +type FileServicesClientListResponse struct { + FileServiceItems +} + +// FileServicesClientSetServicePropertiesResponse contains the response from method FileServicesClient.SetServiceProperties. +type FileServicesClientSetServicePropertiesResponse struct { + // The properties of File services in storage account. + FileServiceProperties +} + +// FileSharesClientCreateResponse contains the response from method FileSharesClient.Create. +type FileSharesClientCreateResponse struct { + // Properties of the file share, including Id, resource name, resource type, Etag. + FileShare +} + +// FileSharesClientDeleteResponse contains the response from method FileSharesClient.Delete. +type FileSharesClientDeleteResponse struct { + // placeholder for future response values +} + +// FileSharesClientGetResponse contains the response from method FileSharesClient.Get. +type FileSharesClientGetResponse struct { + // Properties of the file share, including Id, resource name, resource type, Etag. + FileShare +} + +// FileSharesClientLeaseResponse contains the response from method FileSharesClient.Lease. +type FileSharesClientLeaseResponse struct { + // Lease Share response schema. + LeaseShareResponse + + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// FileSharesClientListResponse contains the response from method FileSharesClient.NewListPager. +type FileSharesClientListResponse struct { + // Response schema. Contains list of shares returned, and if paging is requested or required, a URL to next page of shares. + FileShareItems +} + +// FileSharesClientRestoreResponse contains the response from method FileSharesClient.Restore. +type FileSharesClientRestoreResponse struct { + // placeholder for future response values +} + +// FileSharesClientUpdateResponse contains the response from method FileSharesClient.Update. +type FileSharesClientUpdateResponse struct { + // Properties of the file share, including Id, resource name, resource type, Etag. + FileShare +} + +// LocalUsersClientCreateOrUpdateResponse contains the response from method LocalUsersClient.CreateOrUpdate. +type LocalUsersClientCreateOrUpdateResponse struct { + // The local user associated with the storage accounts. + LocalUser +} + +// LocalUsersClientDeleteResponse contains the response from method LocalUsersClient.Delete. +type LocalUsersClientDeleteResponse struct { + // placeholder for future response values +} + +// LocalUsersClientGetResponse contains the response from method LocalUsersClient.Get. +type LocalUsersClientGetResponse struct { + // The local user associated with the storage accounts. + LocalUser +} + +// LocalUsersClientListKeysResponse contains the response from method LocalUsersClient.ListKeys. +type LocalUsersClientListKeysResponse struct { + // The Storage Account Local User keys. + LocalUserKeys +} + +// LocalUsersClientListResponse contains the response from method LocalUsersClient.NewListPager. +type LocalUsersClientListResponse struct { + // List storage account local users. + LocalUsers +} + +// LocalUsersClientRegeneratePasswordResponse contains the response from method LocalUsersClient.RegeneratePassword. +type LocalUsersClientRegeneratePasswordResponse struct { + // The secrets of Storage Account Local User. + LocalUserRegeneratePasswordResult +} + +// ManagementPoliciesClientCreateOrUpdateResponse contains the response from method ManagementPoliciesClient.CreateOrUpdate. +type ManagementPoliciesClientCreateOrUpdateResponse struct { + // The Get Storage Account ManagementPolicies operation response. + ManagementPolicy +} + +// ManagementPoliciesClientDeleteResponse contains the response from method ManagementPoliciesClient.Delete. +type ManagementPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// ManagementPoliciesClientGetResponse contains the response from method ManagementPoliciesClient.Get. +type ManagementPoliciesClientGetResponse struct { + // The Get Storage Account ManagementPolicies operation response. + ManagementPolicy +} + +// ObjectReplicationPoliciesClientCreateOrUpdateResponse contains the response from method ObjectReplicationPoliciesClient.CreateOrUpdate. +type ObjectReplicationPoliciesClientCreateOrUpdateResponse struct { + // The replication policy between two storage accounts. Multiple rules can be defined in one policy. + ObjectReplicationPolicy +} + +// ObjectReplicationPoliciesClientDeleteResponse contains the response from method ObjectReplicationPoliciesClient.Delete. +type ObjectReplicationPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// ObjectReplicationPoliciesClientGetResponse contains the response from method ObjectReplicationPoliciesClient.Get. +type ObjectReplicationPoliciesClientGetResponse struct { + // The replication policy between two storage accounts. Multiple rules can be defined in one policy. + ObjectReplicationPolicy +} + +// ObjectReplicationPoliciesClientListResponse contains the response from method ObjectReplicationPoliciesClient.NewListPager. +type ObjectReplicationPoliciesClientListResponse struct { + // List storage account object replication policies. + ObjectReplicationPolicies +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // Result of the request to list Storage operations. It contains a list of operations and a URL link to get the next set of + // results. + OperationListResult +} + +// PrivateEndpointConnectionsClientDeleteResponse contains the response from method PrivateEndpointConnectionsClient.Delete. +type PrivateEndpointConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateEndpointConnectionsClientGetResponse contains the response from method PrivateEndpointConnectionsClient.Get. +type PrivateEndpointConnectionsClientGetResponse struct { + // The Private Endpoint Connection resource. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientListResponse contains the response from method PrivateEndpointConnectionsClient.NewListPager. +type PrivateEndpointConnectionsClientListResponse struct { + // List of private endpoint connection associated with the specified storage account + PrivateEndpointConnectionListResult +} + +// PrivateEndpointConnectionsClientPutResponse contains the response from method PrivateEndpointConnectionsClient.Put. +type PrivateEndpointConnectionsClientPutResponse struct { + // The Private Endpoint Connection resource. + PrivateEndpointConnection +} + +// PrivateLinkResourcesClientListByStorageAccountResponse contains the response from method PrivateLinkResourcesClient.ListByStorageAccount. +type PrivateLinkResourcesClientListByStorageAccountResponse struct { + // A list of private link resources + PrivateLinkResourceListResult +} + +// QueueClientCreateResponse contains the response from method QueueClient.Create. +type QueueClientCreateResponse struct { + Queue +} + +// QueueClientDeleteResponse contains the response from method QueueClient.Delete. +type QueueClientDeleteResponse struct { + // placeholder for future response values +} + +// QueueClientGetResponse contains the response from method QueueClient.Get. +type QueueClientGetResponse struct { + Queue +} + +// QueueClientListResponse contains the response from method QueueClient.NewListPager. +type QueueClientListResponse struct { + // Response schema. Contains list of queues returned + ListQueueResource +} + +// QueueClientUpdateResponse contains the response from method QueueClient.Update. +type QueueClientUpdateResponse struct { + Queue +} + +// QueueServicesClientGetServicePropertiesResponse contains the response from method QueueServicesClient.GetServiceProperties. +type QueueServicesClientGetServicePropertiesResponse struct { + // The properties of a storage account’s Queue service. + QueueServiceProperties +} + +// QueueServicesClientListResponse contains the response from method QueueServicesClient.List. +type QueueServicesClientListResponse struct { + ListQueueServices +} + +// QueueServicesClientSetServicePropertiesResponse contains the response from method QueueServicesClient.SetServiceProperties. +type QueueServicesClientSetServicePropertiesResponse struct { + // The properties of a storage account’s Queue service. + QueueServiceProperties +} + +// SKUsClientListResponse contains the response from method SKUsClient.NewListPager. +type SKUsClientListResponse struct { + // The response from the List Storage SKUs operation. + SKUListResult +} + +// TableClientCreateResponse contains the response from method TableClient.Create. +type TableClientCreateResponse struct { + // Properties of the table, including Id, resource name, resource type. + Table +} + +// TableClientDeleteResponse contains the response from method TableClient.Delete. +type TableClientDeleteResponse struct { + // placeholder for future response values +} + +// TableClientGetResponse contains the response from method TableClient.Get. +type TableClientGetResponse struct { + // Properties of the table, including Id, resource name, resource type. + Table +} + +// TableClientListResponse contains the response from method TableClient.NewListPager. +type TableClientListResponse struct { + // Response schema. Contains list of tables returned + ListTableResource +} + +// TableClientUpdateResponse contains the response from method TableClient.Update. +type TableClientUpdateResponse struct { + // Properties of the table, including Id, resource name, resource type. + Table +} + +// TableServicesClientGetServicePropertiesResponse contains the response from method TableServicesClient.GetServiceProperties. +type TableServicesClientGetServicePropertiesResponse struct { + // The properties of a storage account’s Table service. + TableServiceProperties +} + +// TableServicesClientListResponse contains the response from method TableServicesClient.List. +type TableServicesClientListResponse struct { + ListTableServices +} + +// TableServicesClientSetServicePropertiesResponse contains the response from method TableServicesClient.SetServiceProperties. +type TableServicesClientSetServicePropertiesResponse struct { + // The properties of a storage account’s Table service. + TableServiceProperties +} + +// UsagesClientListByLocationResponse contains the response from method UsagesClient.NewListByLocationPager. +type UsagesClientListByLocationResponse struct { + // The response from the List Usages operation. + UsageListResult +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/skus_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/skus_client.go new file mode 100644 index 0000000000..db7979df36 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/skus_client.go @@ -0,0 +1,99 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SKUsClient contains the methods for the SKUs group. +// Don't use this type directly, use NewSKUsClient() instead. +type SKUsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSKUsClient creates a new instance of SKUsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewSKUsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SKUsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SKUsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Lists the available SKUs supported by Microsoft.Storage for given subscription. +// +// Generated from API version 2023-01-01 +// - options - SKUsClientListOptions contains the optional parameters for the SKUsClient.NewListPager method. +func (client *SKUsClient) NewListPager(options *SKUsClientListOptions) *runtime.Pager[SKUsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SKUsClientListResponse]{ + More: func(page SKUsClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *SKUsClientListResponse) (SKUsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SKUsClient.NewListPager") + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return SKUsClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SKUsClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SKUsClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SKUsClient) listCreateRequest(ctx context.Context, options *SKUsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/skus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SKUsClient) listHandleResponse(resp *http.Response) (SKUsClientListResponse, error) { + result := SKUsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SKUListResult); err != nil { + return SKUsClientListResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/table_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/table_client.go new file mode 100644 index 0000000000..169dd385e6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/table_client.go @@ -0,0 +1,395 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TableClient contains the methods for the Table group. +// Don't use this type directly, use NewTableClient() instead. +type TableClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTableClient creates a new instance of TableClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTableClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TableClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TableClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates a new table with the specified table name, under the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - tableName - A table name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of only alphanumeric characters and it cannot begin with a numeric character. +// - options - TableClientCreateOptions contains the optional parameters for the TableClient.Create method. +func (client *TableClient) Create(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientCreateOptions) (TableClientCreateResponse, error) { + var err error + const operationName = "TableClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, tableName, options) + if err != nil { + return TableClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TableClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *TableClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/default/tables/{tableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if tableName == "" { + return nil, errors.New("parameter tableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Parameters != nil { + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *TableClient) createHandleResponse(resp *http.Response) (TableClientCreateResponse, error) { + result := TableClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Table); err != nil { + return TableClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the table with the specified table name, under the specified account if it exists. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - tableName - A table name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of only alphanumeric characters and it cannot begin with a numeric character. +// - options - TableClientDeleteOptions contains the optional parameters for the TableClient.Delete method. +func (client *TableClient) Delete(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientDeleteOptions) (TableClientDeleteResponse, error) { + var err error + const operationName = "TableClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, tableName, options) + if err != nil { + return TableClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return TableClientDeleteResponse{}, err + } + return TableClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TableClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/default/tables/{tableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if tableName == "" { + return nil, errors.New("parameter tableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Gets the table with the specified table name, under the specified account if it exists. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - tableName - A table name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of only alphanumeric characters and it cannot begin with a numeric character. +// - options - TableClientGetOptions contains the optional parameters for the TableClient.Get method. +func (client *TableClient) Get(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientGetOptions) (TableClientGetResponse, error) { + var err error + const operationName = "TableClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, tableName, options) + if err != nil { + return TableClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TableClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TableClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/default/tables/{tableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if tableName == "" { + return nil, errors.New("parameter tableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TableClient) getHandleResponse(resp *http.Response) (TableClientGetResponse, error) { + result := TableClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Table); err != nil { + return TableClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of all the tables under the specified storage account +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - TableClientListOptions contains the optional parameters for the TableClient.NewListPager method. +func (client *TableClient) NewListPager(resourceGroupName string, accountName string, options *TableClientListOptions) *runtime.Pager[TableClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TableClientListResponse]{ + More: func(page TableClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TableClientListResponse) (TableClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TableClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return TableClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TableClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *TableClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/default/tables" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TableClient) listHandleResponse(resp *http.Response) (TableClientListResponse, error) { + result := TableClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListTableResource); err != nil { + return TableClientListResponse{}, err + } + return result, nil +} + +// Update - Creates a new table with the specified table name, under the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - tableName - A table name must be unique within a storage account and must be between 3 and 63 characters.The name must +// comprise of only alphanumeric characters and it cannot begin with a numeric character. +// - options - TableClientUpdateOptions contains the optional parameters for the TableClient.Update method. +func (client *TableClient) Update(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientUpdateOptions) (TableClientUpdateResponse, error) { + var err error + const operationName = "TableClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, tableName, options) + if err != nil { + return TableClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TableClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *TableClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, tableName string, options *TableClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/default/tables/{tableName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if tableName == "" { + return nil, errors.New("parameter tableName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tableName}", url.PathEscape(tableName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Parameters != nil { + if err := runtime.MarshalAsJSON(req, *options.Parameters); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *TableClient) updateHandleResponse(resp *http.Response) (TableClientUpdateResponse, error) { + result := TableClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Table); err != nil { + return TableClientUpdateResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/tableservices_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/tableservices_client.go new file mode 100644 index 0000000000..f53f5f9824 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/tableservices_client.go @@ -0,0 +1,250 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TableServicesClient contains the methods for the TableServices group. +// Don't use this type directly, use NewTableServicesClient() instead. +type TableServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTableServicesClient creates a new instance of TableServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTableServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TableServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TableServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetServiceProperties - Gets the properties of a storage account’s Table service, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - TableServicesClientGetServicePropertiesOptions contains the optional parameters for the TableServicesClient.GetServiceProperties +// method. +func (client *TableServicesClient) GetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, options *TableServicesClientGetServicePropertiesOptions) (TableServicesClientGetServicePropertiesResponse, error) { + var err error + const operationName = "TableServicesClient.GetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return TableServicesClientGetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableServicesClientGetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TableServicesClientGetServicePropertiesResponse{}, err + } + resp, err := client.getServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// getServicePropertiesCreateRequest creates the GetServiceProperties request. +func (client *TableServicesClient) getServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *TableServicesClientGetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/{tableServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{tableServiceName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getServicePropertiesHandleResponse handles the GetServiceProperties response. +func (client *TableServicesClient) getServicePropertiesHandleResponse(resp *http.Response) (TableServicesClientGetServicePropertiesResponse, error) { + result := TableServicesClientGetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TableServiceProperties); err != nil { + return TableServicesClientGetServicePropertiesResponse{}, err + } + return result, nil +} + +// List - List all table services for the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - options - TableServicesClientListOptions contains the optional parameters for the TableServicesClient.List method. +func (client *TableServicesClient) List(ctx context.Context, resourceGroupName string, accountName string, options *TableServicesClientListOptions) (TableServicesClientListResponse, error) { + var err error + const operationName = "TableServicesClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return TableServicesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableServicesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TableServicesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *TableServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *TableServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TableServicesClient) listHandleResponse(resp *http.Response) (TableServicesClientListResponse, error) { + result := TableServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListTableServices); err != nil { + return TableServicesClientListResponse{}, err + } + return result, nil +} + +// SetServiceProperties - Sets the properties of a storage account’s Table service, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-01-01 +// - resourceGroupName - The name of the resource group within the user's subscription. The name is case insensitive. +// - accountName - The name of the storage account within the specified resource group. Storage account names must be between +// 3 and 24 characters in length and use numbers and lower-case letters only. +// - parameters - The properties of a storage account’s Table service, only properties for Storage Analytics and CORS (Cross-Origin +// Resource Sharing) rules can be specified. +// - options - TableServicesClientSetServicePropertiesOptions contains the optional parameters for the TableServicesClient.SetServiceProperties +// method. +func (client *TableServicesClient) SetServiceProperties(ctx context.Context, resourceGroupName string, accountName string, parameters TableServiceProperties, options *TableServicesClientSetServicePropertiesOptions) (TableServicesClientSetServicePropertiesResponse, error) { + var err error + const operationName = "TableServicesClient.SetServiceProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setServicePropertiesCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return TableServicesClientSetServicePropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TableServicesClientSetServicePropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TableServicesClientSetServicePropertiesResponse{}, err + } + resp, err := client.setServicePropertiesHandleResponse(httpResp) + return resp, err +} + +// setServicePropertiesCreateRequest creates the SetServiceProperties request. +func (client *TableServicesClient) setServicePropertiesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters TableServiceProperties, options *TableServicesClientSetServicePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/tableServices/{tableServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + urlPath = strings.ReplaceAll(urlPath, "{tableServiceName}", url.PathEscape("default")) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// setServicePropertiesHandleResponse handles the SetServiceProperties response. +func (client *TableServicesClient) setServicePropertiesHandleResponse(resp *http.Response) (TableServicesClientSetServicePropertiesResponse, error) { + result := TableServicesClientSetServicePropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TableServiceProperties); err != nil { + return TableServicesClientSetServicePropertiesResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/time_rfc3339.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/time_rfc3339.go new file mode 100644 index 0000000000..201ffd2553 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/time_rfc3339.go @@ -0,0 +1,86 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +const ( + utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` + utcDateTime = "2006-01-02T15:04:05.999999999" + dateTimeJSON = `"` + time.RFC3339Nano + `"` +) + +type dateTimeRFC3339 time.Time + +func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t dateTimeRFC3339) MarshalText() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcDateTimeJSON + if tzOffsetRegex.Match(data) { + layout = dateTimeJSON + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { + layout := utcDateTime + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = dateTimeRFC3339(p) + return err +} + +func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*dateTimeRFC3339)(t) +} + +func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || strings.EqualFold(string(data), "null") { + return nil + } + var aux dateTimeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/usages_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/usages_client.go new file mode 100644 index 0000000000..2f4a974fa0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/usages_client.go @@ -0,0 +1,105 @@ +//go:build go1.18 +// +build go1.18 + +// 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. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstorage + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// UsagesClient contains the methods for the Usages group. +// Don't use this type directly, use NewUsagesClient() instead. +type UsagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewUsagesClient creates a new instance of UsagesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewUsagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*UsagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &UsagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByLocationPager - Gets the current usage count and the limit for the resources of the location under the subscription. +// +// Generated from API version 2023-01-01 +// - location - The location of the Azure Storage resource. +// - options - UsagesClientListByLocationOptions contains the optional parameters for the UsagesClient.NewListByLocationPager +// method. +func (client *UsagesClient) NewListByLocationPager(location string, options *UsagesClientListByLocationOptions) *runtime.Pager[UsagesClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[UsagesClientListByLocationResponse]{ + More: func(page UsagesClientListByLocationResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *UsagesClientListByLocationResponse) (UsagesClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "UsagesClient.NewListByLocationPager") + req, err := client.listByLocationCreateRequest(ctx, location, options) + if err != nil { + return UsagesClientListByLocationResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsagesClientListByLocationResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return UsagesClientListByLocationResponse{}, runtime.NewResponseError(resp) + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *UsagesClient) listByLocationCreateRequest(ctx context.Context, location string, options *UsagesClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/locations/{location}/usages" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *UsagesClient) listByLocationHandleResponse(resp *http.Response) (UsagesClientListByLocationResponse, error) { + result := UsagesClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UsageListResult); err != nil { + return UsagesClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/evanphx/json-patch/README.md b/vendor/github.com/evanphx/json-patch/README.md index 28e3516937..97e319b21b 100644 --- a/vendor/github.com/evanphx/json-patch/README.md +++ b/vendor/github.com/evanphx/json-patch/README.md @@ -4,7 +4,7 @@ well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ietf.org/html/rfc7396). [![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) -[![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=master)](https://travis-ci.org/evanphx/json-patch) +[![Build Status](https://github.com/evanphx/json-patch/actions/workflows/go.yml/badge.svg)](https://github.com/evanphx/json-patch/actions/workflows/go.yml) [![Report Card](https://goreportcard.com/badge/github.com/evanphx/json-patch)](https://goreportcard.com/report/github.com/evanphx/json-patch) # Get It! @@ -314,4 +314,4 @@ go test -cover ./... ``` Builds for pull requests are tested automatically -using [TravisCI](https://travis-ci.org/evanphx/json-patch). +using [GitHub Actions](https://github.com/evanphx/json-patch/actions/workflows/go.yml). diff --git a/vendor/github.com/evanphx/json-patch/patch.go b/vendor/github.com/evanphx/json-patch/patch.go index 4bce5936d5..cd0274e1e4 100644 --- a/vendor/github.com/evanphx/json-patch/patch.go +++ b/vendor/github.com/evanphx/json-patch/patch.go @@ -359,7 +359,7 @@ func findObject(pd *container, path string) (container, string) { next, ok := doc.get(decodePatchKey(part)) - if next == nil || ok != nil { + if next == nil || ok != nil || next.raw == nil { return nil, "" } @@ -568,6 +568,29 @@ func (p Patch) replace(doc *container, op Operation) error { return errors.Wrapf(err, "replace operation failed to decode path") } + if path == "" { + val := op.value() + + if val.which == eRaw { + if !val.tryDoc() { + if !val.tryAry() { + return errors.Wrapf(err, "replace operation value must be object or array") + } + } + } + + switch val.which { + case eAry: + *doc = &val.ary + case eDoc: + *doc = &val.doc + case eRaw: + return errors.Wrapf(err, "replace operation hit impossible case") + } + + return nil + } + con, key := findObject(doc, path) if con == nil { @@ -634,6 +657,25 @@ func (p Patch) test(doc *container, op Operation) error { return errors.Wrapf(err, "test operation failed to decode path") } + if path == "" { + var self lazyNode + + switch sv := (*doc).(type) { + case *partialDoc: + self.doc = *sv + self.which = eDoc + case *partialArray: + self.ary = *sv + self.which = eAry + } + + if self.equal(op.value()) { + return nil + } + + return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + } + con, key := findObject(doc, path) if con == nil { @@ -646,7 +688,7 @@ func (p Patch) test(doc *container, op Operation) error { } if val == nil { - if op.value().raw == nil { + if op.value() == nil || op.value().raw == nil { return nil } return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) diff --git a/vendor/github.com/felixge/httpsnoop/.travis.yml b/vendor/github.com/felixge/httpsnoop/.travis.yml deleted file mode 100644 index bfc421200d..0000000000 --- a/vendor/github.com/felixge/httpsnoop/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: go - -go: - - 1.6 - - 1.7 - - 1.8 diff --git a/vendor/github.com/felixge/httpsnoop/Makefile b/vendor/github.com/felixge/httpsnoop/Makefile index 2d84889aed..4e12afdd90 100644 --- a/vendor/github.com/felixge/httpsnoop/Makefile +++ b/vendor/github.com/felixge/httpsnoop/Makefile @@ -1,7 +1,7 @@ .PHONY: ci generate clean ci: clean generate - go test -v ./... + go test -race -v ./... generate: go generate . diff --git a/vendor/github.com/felixge/httpsnoop/README.md b/vendor/github.com/felixge/httpsnoop/README.md index ddcecd13e7..cf6b42f3d7 100644 --- a/vendor/github.com/felixge/httpsnoop/README.md +++ b/vendor/github.com/felixge/httpsnoop/README.md @@ -7,8 +7,8 @@ http.Handlers. Doing this requires non-trivial wrapping of the http.ResponseWriter interface, which is also exposed for users interested in a more low-level API. -[![GoDoc](https://godoc.org/github.com/felixge/httpsnoop?status.svg)](https://godoc.org/github.com/felixge/httpsnoop) -[![Build Status](https://travis-ci.org/felixge/httpsnoop.svg?branch=master)](https://travis-ci.org/felixge/httpsnoop) +[![Go Reference](https://pkg.go.dev/badge/github.com/felixge/httpsnoop.svg)](https://pkg.go.dev/github.com/felixge/httpsnoop) +[![Build Status](https://github.com/felixge/httpsnoop/actions/workflows/main.yaml/badge.svg)](https://github.com/felixge/httpsnoop/actions/workflows/main.yaml) ## Usage Example diff --git a/vendor/github.com/felixge/httpsnoop/capture_metrics.go b/vendor/github.com/felixge/httpsnoop/capture_metrics.go index b77cc7c009..bec7b71b39 100644 --- a/vendor/github.com/felixge/httpsnoop/capture_metrics.go +++ b/vendor/github.com/felixge/httpsnoop/capture_metrics.go @@ -52,7 +52,7 @@ func (m *Metrics) CaptureMetrics(w http.ResponseWriter, fn func(http.ResponseWri return func(code int) { next(code) - if !headerWritten { + if !(code >= 100 && code <= 199) && !headerWritten { m.Code = code headerWritten = true } diff --git a/vendor/github.com/felixge/httpsnoop/wrap_generated_gteq_1.8.go b/vendor/github.com/felixge/httpsnoop/wrap_generated_gteq_1.8.go index 31cbdfb8ef..101cedde67 100644 --- a/vendor/github.com/felixge/httpsnoop/wrap_generated_gteq_1.8.go +++ b/vendor/github.com/felixge/httpsnoop/wrap_generated_gteq_1.8.go @@ -1,5 +1,5 @@ // +build go1.8 -// Code generated by "httpsnoop/codegen"; DO NOT EDIT +// Code generated by "httpsnoop/codegen"; DO NOT EDIT. package httpsnoop diff --git a/vendor/github.com/felixge/httpsnoop/wrap_generated_lt_1.8.go b/vendor/github.com/felixge/httpsnoop/wrap_generated_lt_1.8.go index ab99c07c7a..e0951df152 100644 --- a/vendor/github.com/felixge/httpsnoop/wrap_generated_lt_1.8.go +++ b/vendor/github.com/felixge/httpsnoop/wrap_generated_lt_1.8.go @@ -1,5 +1,5 @@ // +build !go1.8 -// Code generated by "httpsnoop/codegen"; DO NOT EDIT +// Code generated by "httpsnoop/codegen"; DO NOT EDIT. package httpsnoop diff --git a/vendor/github.com/fsnotify/fsnotify/.cirrus.yml b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml new file mode 100644 index 0000000000..ffc7b992b3 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml @@ -0,0 +1,13 @@ +freebsd_task: + name: 'FreeBSD' + freebsd_instance: + image_family: freebsd-13-2 + install_script: + - pkg update -f + - pkg install -y go + test_script: + # run tests as user "cirrus" instead of root + - pw useradd cirrus -m + - chown -R cirrus:cirrus . + - FSNOTIFY_BUFFER=4096 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... + - sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore index 1d89d85ce4..391cc076b1 100644 --- a/vendor/github.com/fsnotify/fsnotify/.gitignore +++ b/vendor/github.com/fsnotify/fsnotify/.gitignore @@ -4,3 +4,4 @@ # Output of go build ./cmd/fsnotify /fsnotify +/fsnotify.exe diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md index 77f9593bd5..e0e5757549 100644 --- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md +++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md @@ -1,16 +1,87 @@ # Changelog -All notable changes to this project will be documented in this file. +Unreleased +---------- +Nothing yet. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +1.7.0 - 2023-10-22 +------------------ +This version of fsnotify needs Go 1.17. -## [Unreleased] +### Additions -Nothing yet. +- illumos: add FEN backend to support illumos and Solaris. ([#371]) + +- all: add `NewBufferedWatcher()` to use a buffered channel, which can be useful + in cases where you can't control the kernel buffer and receive a large number + of events in bursts. ([#550], [#572]) + +- all: add `AddWith()`, which is identical to `Add()` but allows passing + options. ([#521]) + +- windows: allow setting the ReadDirectoryChangesW() buffer size with + `fsnotify.WithBufferSize()`; the default of 64K is the highest value that + works on all platforms and is enough for most purposes, but in some cases a + highest buffer is needed. ([#521]) + +### Changes and fixes + +- inotify: remove watcher if a watched path is renamed ([#518]) + + After a rename the reported name wasn't updated, or even an empty string. + Inotify doesn't provide any good facilities to update it, so just remove the + watcher. This is already how it worked on kqueue and FEN. + + On Windows this does work, and remains working. + +- windows: don't listen for file attribute changes ([#520]) + + File attribute changes are sent as `FILE_ACTION_MODIFIED` by the Windows API, + with no way to see if they're a file write or attribute change, so would show + up as a fsnotify.Write event. This is never useful, and could result in many + spurious Write events. + +- windows: return `ErrEventOverflow` if the buffer is full ([#525]) + + Before it would merely return "short read", making it hard to detect this + error. + +- kqueue: make sure events for all files are delivered properly when removing a + watched directory ([#526]) + + Previously they would get sent with `""` (empty string) or `"."` as the path + name. + +- kqueue: don't emit spurious Create events for symbolic links ([#524]) + + The link would get resolved but kqueue would "forget" it already saw the link + itself, resulting on a Create for every Write event for the directory. + +- all: return `ErrClosed` on `Add()` when the watcher is closed ([#516]) + +- other: add `Watcher.Errors` and `Watcher.Events` to the no-op `Watcher` in + `backend_other.go`, making it easier to use on unsupported platforms such as + WASM, AIX, etc. ([#528]) + +- other: use the `backend_other.go` no-op if the `appengine` build tag is set; + Google AppEngine forbids usage of the unsafe package so the inotify backend + won't compile there. -## [1.6.0] - 2022-10-13 +[#371]: https://github.com/fsnotify/fsnotify/pull/371 +[#516]: https://github.com/fsnotify/fsnotify/pull/516 +[#518]: https://github.com/fsnotify/fsnotify/pull/518 +[#520]: https://github.com/fsnotify/fsnotify/pull/520 +[#521]: https://github.com/fsnotify/fsnotify/pull/521 +[#524]: https://github.com/fsnotify/fsnotify/pull/524 +[#525]: https://github.com/fsnotify/fsnotify/pull/525 +[#526]: https://github.com/fsnotify/fsnotify/pull/526 +[#528]: https://github.com/fsnotify/fsnotify/pull/528 +[#537]: https://github.com/fsnotify/fsnotify/pull/537 +[#550]: https://github.com/fsnotify/fsnotify/pull/550 +[#572]: https://github.com/fsnotify/fsnotify/pull/572 +1.6.0 - 2022-10-13 +------------------ This version of fsnotify needs Go 1.16 (this was already the case since 1.5.1, but not documented). It also increases the minimum Linux version to 2.6.32. diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md index d4e6080feb..e480733d16 100644 --- a/vendor/github.com/fsnotify/fsnotify/README.md +++ b/vendor/github.com/fsnotify/fsnotify/README.md @@ -1,29 +1,31 @@ fsnotify is a Go library to provide cross-platform filesystem notifications on -Windows, Linux, macOS, and BSD systems. +Windows, Linux, macOS, BSD, and illumos. -Go 1.16 or newer is required; the full documentation is at +Go 1.17 or newer is required; the full documentation is at https://pkg.go.dev/github.com/fsnotify/fsnotify -**It's best to read the documentation at pkg.go.dev, as it's pinned to the last -released version, whereas this README is for the last development version which -may include additions/changes.** - --- Platform support: -| Adapter | OS | Status | -| --------------------- | ---------------| -------------------------------------------------------------| -| inotify | Linux 2.6.32+ | Supported | -| kqueue | BSD, macOS | Supported | -| ReadDirectoryChangesW | Windows | Supported | -| FSEvents | macOS | [Planned](https://github.com/fsnotify/fsnotify/issues/11) | -| FEN | Solaris 11 | [In Progress](https://github.com/fsnotify/fsnotify/pull/371) | -| fanotify | Linux 5.9+ | [Maybe](https://github.com/fsnotify/fsnotify/issues/114) | -| USN Journals | Windows | [Maybe](https://github.com/fsnotify/fsnotify/issues/53) | -| Polling | *All* | [Maybe](https://github.com/fsnotify/fsnotify/issues/9) | - -Linux and macOS should include Android and iOS, but these are currently untested. +| Backend | OS | Status | +| :-------------------- | :--------- | :------------------------------------------------------------------------ | +| inotify | Linux | Supported | +| kqueue | BSD, macOS | Supported | +| ReadDirectoryChangesW | Windows | Supported | +| FEN | illumos | Supported | +| fanotify | Linux 5.9+ | [Not yet](https://github.com/fsnotify/fsnotify/issues/114) | +| AHAFS | AIX | [aix branch]; experimental due to lack of maintainer and test environment | +| FSEvents | macOS | [Needs support in x/sys/unix][fsevents] | +| USN Journals | Windows | [Needs support in x/sys/windows][usn] | +| Polling | *All* | [Not yet](https://github.com/fsnotify/fsnotify/issues/9) | + +Linux and illumos should include Android and Solaris, but these are currently +untested. + +[fsevents]: https://github.com/fsnotify/fsnotify/issues/11#issuecomment-1279133120 +[usn]: https://github.com/fsnotify/fsnotify/issues/53#issuecomment-1279829847 +[aix branch]: https://github.com/fsnotify/fsnotify/issues/353#issuecomment-1284590129 Usage ----- @@ -83,20 +85,23 @@ run with: % go run ./cmd/fsnotify +Further detailed documentation can be found in godoc: +https://pkg.go.dev/github.com/fsnotify/fsnotify + FAQ --- ### Will a file still be watched when it's moved to another directory? No, not unless you are watching the location it was moved to. -### Are subdirectories watched too? +### Are subdirectories watched? No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap: [#18]). [#18]: https://github.com/fsnotify/fsnotify/issues/18 ### Do I have to watch the Error and Event channels in a goroutine? -As of now, yes (you can read both channels in the same goroutine using `select`, -you don't need a separate goroutine for both channels; see the example). +Yes. You can read both channels in the same goroutine using `select` (you don't +need a separate goroutine for both channels; see the example). ### Why don't notifications work with NFS, SMB, FUSE, /proc, or /sys? fsnotify requires support from underlying OS to work. The current NFS and SMB @@ -107,6 +112,32 @@ This could be fixed with a polling watcher ([#9]), but it's not yet implemented. [#9]: https://github.com/fsnotify/fsnotify/issues/9 +### Why do I get many Chmod events? +Some programs may generate a lot of attribute changes; for example Spotlight on +macOS, anti-virus programs, backup applications, and some others are known to do +this. As a rule, it's typically best to ignore Chmod events. They're often not +useful, and tend to cause problems. + +Spotlight indexing on macOS can result in multiple events (see [#15]). A +temporary workaround is to add your folder(s) to the *Spotlight Privacy +settings* until we have a native FSEvents implementation (see [#11]). + +[#11]: https://github.com/fsnotify/fsnotify/issues/11 +[#15]: https://github.com/fsnotify/fsnotify/issues/15 + +### Watching a file doesn't work well +Watching individual files (rather than directories) is generally not recommended +as many programs (especially editors) update files atomically: it will write to +a temporary file which is then moved to to destination, overwriting the original +(or some variant thereof). The watcher on the original file is now lost, as that +no longer exists. + +The upshot of this is that a power failure or crash won't leave a half-written +file. + +Watch the parent directory and use `Event.Name` to filter out files you're not +interested in. There is an example of this in `cmd/fsnotify/file.go`. + Platform-specific notes ----------------------- ### Linux @@ -151,11 +182,3 @@ these platforms. The sysctl variables `kern.maxfiles` and `kern.maxfilesperproc` can be used to control the maximum number of open files. - -### macOS -Spotlight indexing on macOS can result in multiple events (see [#15]). A temporary -workaround is to add your folder(s) to the *Spotlight Privacy settings* until we -have a native FSEvents implementation (see [#11]). - -[#11]: https://github.com/fsnotify/fsnotify/issues/11 -[#15]: https://github.com/fsnotify/fsnotify/issues/15 diff --git a/vendor/github.com/fsnotify/fsnotify/backend_fen.go b/vendor/github.com/fsnotify/fsnotify/backend_fen.go index 1a95ad8e7c..28497f1dd8 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_fen.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_fen.go @@ -1,10 +1,19 @@ //go:build solaris // +build solaris +// Note: the documentation on the Watcher type and methods is generated from +// mkdoc.zsh + package fsnotify import ( "errors" + "fmt" + "os" + "path/filepath" + "sync" + + "golang.org/x/sys/unix" ) // Watcher watches a set of paths, delivering events on a channel. @@ -17,9 +26,9 @@ import ( // When a file is removed a Remove event won't be emitted until all file // descriptors are closed, and deletes will always emit a Chmod. For example: // -// fp := os.Open("file") -// os.Remove("file") // Triggers Chmod -// fp.Close() // Triggers Remove +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove // // This is the event that inotify sends, so not much can be changed about this. // @@ -33,16 +42,16 @@ import ( // // To increase them you can use sysctl or write the value to the /proc file: // -// # Default values on Linux 5.18 -// sysctl fs.inotify.max_user_watches=124983 -// sysctl fs.inotify.max_user_instances=128 +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 // // To make the changes persist on reboot edit /etc/sysctl.conf or // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check // your distro's documentation): // -// fs.inotify.max_user_watches=124983 -// fs.inotify.max_user_instances=128 +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 // // Reaching the limit will result in a "no space left on device" or "too many open // files" error. @@ -58,14 +67,20 @@ import ( // control the maximum number of open files, as well as /etc/login.conf on BSD // systems. // -// # macOS notes +// # Windows notes +// +// Paths can be added as "C:\path\to\dir", but forward slashes +// ("C:/path/to/dir") will also work. // -// Spotlight indexing on macOS can result in multiple events (see [#15]). A -// temporary workaround is to add your folder(s) to the "Spotlight Privacy -// Settings" until we have a native FSEvents implementation (see [#11]). +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all times, sometimes it will send no +// events, and often only for some files. // -// [#11]: https://github.com/fsnotify/fsnotify/issues/11 -// [#15]: https://github.com/fsnotify/fsnotify/issues/15 +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. type Watcher struct { // Events sends the filesystem change events. // @@ -92,44 +107,129 @@ type Watcher struct { // initiated by the user may show up as one or multiple // writes, depending on when the system syncs things to // disk. For example when compiling a large Go program - // you may get hundreds of Write events, so you - // probably want to wait until you've stopped receiving - // them (see the dedup example in cmd/fsnotify). + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. // // fsnotify.Chmod Attributes were changed. On Linux this is also sent // when a file is removed (or more accurately, when a // link to an inode is removed). On kqueue it's sent - // and on kqueue when a file is truncated. On Windows - // it's never sent. + // when a file is truncated. On Windows it's never + // sent. Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. Errors chan error + + mu sync.Mutex + port *unix.EventPort + done chan struct{} // Channel for sending a "quit message" to the reader goroutine + dirs map[string]struct{} // Explicitly watched directories + watches map[string]struct{} // Explicitly watched non-directories } // NewWatcher creates a new Watcher. func NewWatcher() (*Watcher, error) { - return nil, errors.New("FEN based watcher not yet supported for fsnotify\n") + return NewBufferedWatcher(0) } -// Close removes all watches and closes the events channel. +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { + w := &Watcher{ + Events: make(chan Event, sz), + Errors: make(chan error), + dirs: make(map[string]struct{}), + watches: make(map[string]struct{}), + done: make(chan struct{}), + } + + var err error + w.port, err = unix.NewEventPort() + if err != nil { + return nil, fmt.Errorf("fsnotify.NewWatcher: %w", err) + } + + go w.readEvents() + return w, nil +} + +// sendEvent attempts to send an event to the user, returning true if the event +// was put in the channel successfully and false if the watcher has been closed. +func (w *Watcher) sendEvent(name string, op Op) (sent bool) { + select { + case w.Events <- Event{Name: name, Op: op}: + return true + case <-w.done: + return false + } +} + +// sendError attempts to send an error to the user, returning true if the error +// was put in the channel successfully and false if the watcher has been closed. +func (w *Watcher) sendError(err error) (sent bool) { + select { + case w.Errors <- err: + return true + case <-w.done: + return false + } +} + +func (w *Watcher) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } +} + +// Close removes all watches and closes the Events channel. func (w *Watcher) Close() error { - return nil + // Take the lock used by associateFile to prevent lingering events from + // being processed after the close + w.mu.Lock() + defer w.mu.Unlock() + if w.isClosed() { + return nil + } + close(w.done) + return w.port.Close() } // Add starts monitoring the path for changes. // -// A path can only be watched once; attempting to watch it more than once will -// return an error. Paths that do not yet exist on the filesystem cannot be -// added. A watch will be automatically removed if the path is deleted. +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. // -// A path will remain watched if it gets renamed to somewhere else on the same -// filesystem, but the monitor will get removed if the path gets deleted and -// re-created, or if it's moved to a different filesystem. +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. // // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special // filesystems (/proc, /sys, etc.) generally don't work. // +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// // # Watching directories // // All files in a directory are monitored, including new files that are created @@ -139,15 +239,63 @@ func (w *Watcher) Close() error { // # Watching files // // Watching individual files (rather than directories) is generally not -// recommended as many tools update files atomically. Instead of "just" writing -// to the file a temporary file will be written to first, and if successful the -// temporary file is moved to to destination removing the original, or some -// variant thereof. The watcher on the original file is now lost, as it no -// longer exists. -// -// Instead, watch the parent directory and use Event.Name to filter out files -// you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. -func (w *Watcher) Add(name string) error { +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(name string) error { return w.AddWith(name) } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if w.port.PathIsWatched(name) { + return nil + } + + _ = getOptions(opts...) + + // Currently we resolve symlinks that were explicitly requested to be + // watched. Otherwise we would use LStat here. + stat, err := os.Stat(name) + if err != nil { + return err + } + + // Associate all files in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, true, w.associateFile) + if err != nil { + return err + } + + w.mu.Lock() + w.dirs[name] = struct{}{} + w.mu.Unlock() + return nil + } + + err = w.associateFile(name, stat, true) + if err != nil { + return err + } + + w.mu.Lock() + w.watches[name] = struct{}{} + w.mu.Unlock() return nil } @@ -157,6 +305,336 @@ func (w *Watcher) Add(name string) error { // /tmp/dir and /tmp/dir/subdir then you will need to remove both. // // Removing a path that has not yet been added returns [ErrNonExistentWatch]. +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) Remove(name string) error { + if w.isClosed() { + return nil + } + if !w.port.PathIsWatched(name) { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } + + // The user has expressed an intent. Immediately remove this name from + // whichever watch list it might be in. If it's not in there the delete + // doesn't cause harm. + w.mu.Lock() + delete(w.watches, name) + delete(w.dirs, name) + w.mu.Unlock() + + stat, err := os.Stat(name) + if err != nil { + return err + } + + // Remove associations for every file in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, false, w.dissociateFile) + if err != nil { + return err + } + return nil + } + + err = w.port.DissociatePath(name) + if err != nil { + return err + } + return nil } + +// readEvents contains the main loop that runs in a goroutine watching for events. +func (w *Watcher) readEvents() { + // If this function returns, the watcher has been closed and we can close + // these channels + defer func() { + close(w.Errors) + close(w.Events) + }() + + pevents := make([]unix.PortEvent, 8) + for { + count, err := w.port.Get(pevents, 1, nil) + if err != nil && err != unix.ETIME { + // Interrupted system call (count should be 0) ignore and continue + if errors.Is(err, unix.EINTR) && count == 0 { + continue + } + // Get failed because we called w.Close() + if errors.Is(err, unix.EBADF) && w.isClosed() { + return + } + // There was an error not caused by calling w.Close() + if !w.sendError(err) { + return + } + } + + p := pevents[:count] + for _, pevent := range p { + if pevent.Source != unix.PORT_SOURCE_FILE { + // Event from unexpected source received; should never happen. + if !w.sendError(errors.New("Event from unexpected source received")) { + return + } + continue + } + + err = w.handleEvent(&pevent) + if err != nil { + if !w.sendError(err) { + return + } + } + } + } +} + +func (w *Watcher) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error { + files, err := os.ReadDir(path) + if err != nil { + return err + } + + // Handle all children of the directory. + for _, entry := range files { + finfo, err := entry.Info() + if err != nil { + return err + } + err = handler(filepath.Join(path, finfo.Name()), finfo, false) + if err != nil { + return err + } + } + + // And finally handle the directory itself. + return handler(path, stat, follow) +} + +// handleEvent might need to emit more than one fsnotify event if the events +// bitmap matches more than one event type (e.g. the file was both modified and +// had the attributes changed between when the association was created and the +// when event was returned) +func (w *Watcher) handleEvent(event *unix.PortEvent) error { + var ( + events = event.Events + path = event.Path + fmode = event.Cookie.(os.FileMode) + reRegister = true + ) + + w.mu.Lock() + _, watchedDir := w.dirs[path] + _, watchedPath := w.watches[path] + w.mu.Unlock() + isWatched := watchedDir || watchedPath + + if events&unix.FILE_DELETE != 0 { + if !w.sendEvent(path, Remove) { + return nil + } + reRegister = false + } + if events&unix.FILE_RENAME_FROM != 0 { + if !w.sendEvent(path, Rename) { + return nil + } + // Don't keep watching the new file name + reRegister = false + } + if events&unix.FILE_RENAME_TO != 0 { + // We don't report a Rename event for this case, because Rename events + // are interpreted as referring to the _old_ name of the file, and in + // this case the event would refer to the new name of the file. This + // type of rename event is not supported by fsnotify. + + // inotify reports a Remove event in this case, so we simulate this + // here. + if !w.sendEvent(path, Remove) { + return nil + } + // Don't keep watching the file that was removed + reRegister = false + } + + // The file is gone, nothing left to do. + if !reRegister { + if watchedDir { + w.mu.Lock() + delete(w.dirs, path) + w.mu.Unlock() + } + if watchedPath { + w.mu.Lock() + delete(w.watches, path) + w.mu.Unlock() + } + return nil + } + + // If we didn't get a deletion the file still exists and we're going to have + // to watch it again. Let's Stat it now so that we can compare permissions + // and have what we need to continue watching the file + + stat, err := os.Lstat(path) + if err != nil { + // This is unexpected, but we should still emit an event. This happens + // most often on "rm -r" of a subdirectory inside a watched directory We + // get a modify event of something happening inside, but by the time we + // get here, the sudirectory is already gone. Clearly we were watching + // this path but now it is gone. Let's tell the user that it was + // removed. + if !w.sendEvent(path, Remove) { + return nil + } + // Suppress extra write events on removed directories; they are not + // informative and can be confusing. + return nil + } + + // resolve symlinks that were explicitly watched as we would have at Add() + // time. this helps suppress spurious Chmod events on watched symlinks + if isWatched { + stat, err = os.Stat(path) + if err != nil { + // The symlink still exists, but the target is gone. Report the + // Remove similar to above. + if !w.sendEvent(path, Remove) { + return nil + } + // Don't return the error + } + } + + if events&unix.FILE_MODIFIED != 0 { + if fmode.IsDir() { + if watchedDir { + if err := w.updateDirectory(path); err != nil { + return err + } + } else { + if !w.sendEvent(path, Write) { + return nil + } + } + } else { + if !w.sendEvent(path, Write) { + return nil + } + } + } + if events&unix.FILE_ATTRIB != 0 && stat != nil { + // Only send Chmod if perms changed + if stat.Mode().Perm() != fmode.Perm() { + if !w.sendEvent(path, Chmod) { + return nil + } + } + } + + if stat != nil { + // If we get here, it means we've hit an event above that requires us to + // continue watching the file or directory + return w.associateFile(path, stat, isWatched) + } + return nil +} + +func (w *Watcher) updateDirectory(path string) error { + // The directory was modified, so we must find unwatched entities and watch + // them. If something was removed from the directory, nothing will happen, + // as everything else should still be watched. + files, err := os.ReadDir(path) + if err != nil { + return err + } + + for _, entry := range files { + path := filepath.Join(path, entry.Name()) + if w.port.PathIsWatched(path) { + continue + } + + finfo, err := entry.Info() + if err != nil { + return err + } + err = w.associateFile(path, finfo, false) + if err != nil { + if !w.sendError(err) { + return nil + } + } + if !w.sendEvent(path, Create) { + return nil + } + } + return nil +} + +func (w *Watcher) associateFile(path string, stat os.FileInfo, follow bool) error { + if w.isClosed() { + return ErrClosed + } + // This is primarily protecting the call to AssociatePath but it is + // important and intentional that the call to PathIsWatched is also + // protected by this mutex. Without this mutex, AssociatePath has been seen + // to error out that the path is already associated. + w.mu.Lock() + defer w.mu.Unlock() + + if w.port.PathIsWatched(path) { + // Remove the old association in favor of this one If we get ENOENT, + // then while the x/sys/unix wrapper still thought that this path was + // associated, the underlying event port did not. This call will have + // cleared up that discrepancy. The most likely cause is that the event + // has fired but we haven't processed it yet. + err := w.port.DissociatePath(path) + if err != nil && err != unix.ENOENT { + return err + } + } + // FILE_NOFOLLOW means we watch symlinks themselves rather than their + // targets. + events := unix.FILE_MODIFIED | unix.FILE_ATTRIB | unix.FILE_NOFOLLOW + if follow { + // We *DO* follow symlinks for explicitly watched entries. + events = unix.FILE_MODIFIED | unix.FILE_ATTRIB + } + return w.port.AssociatePath(path, stat, + events, + stat.Mode()) +} + +func (w *Watcher) dissociateFile(path string, stat os.FileInfo, unused bool) error { + if !w.port.PathIsWatched(path) { + return nil + } + return w.port.DissociatePath(path) +} + +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// Returns nil if [Watcher.Close] was called. +func (w *Watcher) WatchList() []string { + if w.isClosed() { + return nil + } + + w.mu.Lock() + defer w.mu.Unlock() + + entries := make([]string, 0, len(w.watches)+len(w.dirs)) + for pathname := range w.dirs { + entries = append(entries, pathname) + } + for pathname := range w.watches { + entries = append(entries, pathname) + } + + return entries +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go index 54c77fbb0e..921c1c1e40 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go @@ -1,5 +1,8 @@ -//go:build linux -// +build linux +//go:build linux && !appengine +// +build linux,!appengine + +// Note: the documentation on the Watcher type and methods is generated from +// mkdoc.zsh package fsnotify @@ -26,9 +29,9 @@ import ( // When a file is removed a Remove event won't be emitted until all file // descriptors are closed, and deletes will always emit a Chmod. For example: // -// fp := os.Open("file") -// os.Remove("file") // Triggers Chmod -// fp.Close() // Triggers Remove +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove // // This is the event that inotify sends, so not much can be changed about this. // @@ -42,16 +45,16 @@ import ( // // To increase them you can use sysctl or write the value to the /proc file: // -// # Default values on Linux 5.18 -// sysctl fs.inotify.max_user_watches=124983 -// sysctl fs.inotify.max_user_instances=128 +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 // // To make the changes persist on reboot edit /etc/sysctl.conf or // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check // your distro's documentation): // -// fs.inotify.max_user_watches=124983 -// fs.inotify.max_user_instances=128 +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 // // Reaching the limit will result in a "no space left on device" or "too many open // files" error. @@ -67,14 +70,20 @@ import ( // control the maximum number of open files, as well as /etc/login.conf on BSD // systems. // -// # macOS notes +// # Windows notes +// +// Paths can be added as "C:\path\to\dir", but forward slashes +// ("C:/path/to/dir") will also work. // -// Spotlight indexing on macOS can result in multiple events (see [#15]). A -// temporary workaround is to add your folder(s) to the "Spotlight Privacy -// Settings" until we have a native FSEvents implementation (see [#11]). +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all times, sometimes it will send no +// events, and often only for some files. // -// [#11]: https://github.com/fsnotify/fsnotify/issues/11 -// [#15]: https://github.com/fsnotify/fsnotify/issues/15 +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. type Watcher struct { // Events sends the filesystem change events. // @@ -101,36 +110,148 @@ type Watcher struct { // initiated by the user may show up as one or multiple // writes, depending on when the system syncs things to // disk. For example when compiling a large Go program - // you may get hundreds of Write events, so you - // probably want to wait until you've stopped receiving - // them (see the dedup example in cmd/fsnotify). + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. // // fsnotify.Chmod Attributes were changed. On Linux this is also sent // when a file is removed (or more accurately, when a // link to an inode is removed). On kqueue it's sent - // and on kqueue when a file is truncated. On Windows - // it's never sent. + // when a file is truncated. On Windows it's never + // sent. Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. Errors chan error // Store fd here as os.File.Read() will no longer return on close after // calling Fd(). See: https://github.com/golang/go/issues/26439 fd int - mu sync.Mutex // Map access inotifyFile *os.File - watches map[string]*watch // Map of inotify watches (key: path) - paths map[int]string // Map of watched paths (key: watch descriptor) - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - doneResp chan struct{} // Channel to respond to Close + watches *watches + done chan struct{} // Channel for sending a "quit message" to the reader goroutine + closeMu sync.Mutex + doneResp chan struct{} // Channel to respond to Close +} + +type ( + watches struct { + mu sync.RWMutex + wd map[uint32]*watch // wd → watch + path map[string]uint32 // pathname → wd + } + watch struct { + wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) + flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) + path string // Watch path. + } +) + +func newWatches() *watches { + return &watches{ + wd: make(map[uint32]*watch), + path: make(map[string]uint32), + } +} + +func (w *watches) len() int { + w.mu.RLock() + defer w.mu.RUnlock() + return len(w.wd) +} + +func (w *watches) add(ww *watch) { + w.mu.Lock() + defer w.mu.Unlock() + w.wd[ww.wd] = ww + w.path[ww.path] = ww.wd +} + +func (w *watches) remove(wd uint32) { + w.mu.Lock() + defer w.mu.Unlock() + delete(w.path, w.wd[wd].path) + delete(w.wd, wd) +} + +func (w *watches) removePath(path string) (uint32, bool) { + w.mu.Lock() + defer w.mu.Unlock() + + wd, ok := w.path[path] + if !ok { + return 0, false + } + + delete(w.path, path) + delete(w.wd, wd) + + return wd, true +} + +func (w *watches) byPath(path string) *watch { + w.mu.RLock() + defer w.mu.RUnlock() + return w.wd[w.path[path]] +} + +func (w *watches) byWd(wd uint32) *watch { + w.mu.RLock() + defer w.mu.RUnlock() + return w.wd[wd] +} + +func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error { + w.mu.Lock() + defer w.mu.Unlock() + + var existing *watch + wd, ok := w.path[path] + if ok { + existing = w.wd[wd] + } + + upd, err := f(existing) + if err != nil { + return err + } + if upd != nil { + w.wd[upd.wd] = upd + w.path[upd.path] = upd.wd + + if upd.wd != wd { + delete(w.wd, wd) + } + } + + return nil } // NewWatcher creates a new Watcher. func NewWatcher() (*Watcher, error) { - // Create inotify fd - // Need to set the FD to nonblocking mode in order for SetDeadline methods to work - // Otherwise, blocking i/o operations won't terminate on close + return NewBufferedWatcher(0) +} + +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { + // Need to set nonblocking mode for SetDeadline to work, otherwise blocking + // I/O operations won't terminate on close. fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) if fd == -1 { return nil, errno @@ -139,9 +260,8 @@ func NewWatcher() (*Watcher, error) { w := &Watcher{ fd: fd, inotifyFile: os.NewFile(uintptr(fd), ""), - watches: make(map[string]*watch), - paths: make(map[int]string), - Events: make(chan Event), + watches: newWatches(), + Events: make(chan Event, sz), Errors: make(chan error), done: make(chan struct{}), doneResp: make(chan struct{}), @@ -157,8 +277,8 @@ func (w *Watcher) sendEvent(e Event) bool { case w.Events <- e: return true case <-w.done: + return false } - return false } // Returns true if the error was sent, or false if watcher is closed. @@ -180,17 +300,15 @@ func (w *Watcher) isClosed() bool { } } -// Close removes all watches and closes the events channel. +// Close removes all watches and closes the Events channel. func (w *Watcher) Close() error { - w.mu.Lock() + w.closeMu.Lock() if w.isClosed() { - w.mu.Unlock() + w.closeMu.Unlock() return nil } - - // Send 'close' signal to goroutine, and set the Watcher to closed. close(w.done) - w.mu.Unlock() + w.closeMu.Unlock() // Causes any blocking reads to return with an error, provided the file // still supports deadline operations. @@ -207,17 +325,21 @@ func (w *Watcher) Close() error { // Add starts monitoring the path for changes. // -// A path can only be watched once; attempting to watch it more than once will -// return an error. Paths that do not yet exist on the filesystem cannot be -// added. A watch will be automatically removed if the path is deleted. +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. // -// A path will remain watched if it gets renamed to somewhere else on the same -// filesystem, but the monitor will get removed if the path gets deleted and -// re-created, or if it's moved to a different filesystem. +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. // // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special // filesystems (/proc, /sys, etc.) generally don't work. // +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// // # Watching directories // // All files in a directory are monitored, including new files that are created @@ -227,44 +349,59 @@ func (w *Watcher) Close() error { // # Watching files // // Watching individual files (rather than directories) is generally not -// recommended as many tools update files atomically. Instead of "just" writing -// to the file a temporary file will be written to first, and if successful the -// temporary file is moved to to destination removing the original, or some -// variant thereof. The watcher on the original file is now lost, as it no -// longer exists. -// -// Instead, watch the parent directory and use Event.Name to filter out files -// you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. -func (w *Watcher) Add(name string) error { - name = filepath.Clean(name) +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(name string) error { return w.AddWith(name) } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(name string, opts ...addOpt) error { if w.isClosed() { - return errors.New("inotify instance already closed") + return ErrClosed } + name = filepath.Clean(name) + _ = getOptions(opts...) + var flags uint32 = unix.IN_MOVED_TO | unix.IN_MOVED_FROM | unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY | unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF - w.mu.Lock() - defer w.mu.Unlock() - watchEntry := w.watches[name] - if watchEntry != nil { - flags |= watchEntry.flags | unix.IN_MASK_ADD - } - wd, errno := unix.InotifyAddWatch(w.fd, name, flags) - if wd == -1 { - return errno - } + return w.watches.updatePath(name, func(existing *watch) (*watch, error) { + if existing != nil { + flags |= existing.flags | unix.IN_MASK_ADD + } - if watchEntry == nil { - w.watches[name] = &watch{wd: uint32(wd), flags: flags} - w.paths[wd] = name - } else { - watchEntry.wd = uint32(wd) - watchEntry.flags = flags - } + wd, err := unix.InotifyAddWatch(w.fd, name, flags) + if wd == -1 { + return nil, err + } - return nil + if existing == nil { + return &watch{ + wd: uint32(wd), + path: name, + flags: flags, + }, nil + } + + existing.wd = uint32(wd) + existing.flags = flags + return existing, nil + }) } // Remove stops monitoring the path for changes. @@ -273,32 +410,22 @@ func (w *Watcher) Add(name string) error { // /tmp/dir and /tmp/dir/subdir then you will need to remove both. // // Removing a path that has not yet been added returns [ErrNonExistentWatch]. +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - - // Fetch the watch. - w.mu.Lock() - defer w.mu.Unlock() - watch, ok := w.watches[name] + if w.isClosed() { + return nil + } + return w.remove(filepath.Clean(name)) +} - // Remove it from inotify. +func (w *Watcher) remove(name string) error { + wd, ok := w.watches.removePath(name) if !ok { return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) } - // We successfully removed the watch if InotifyRmWatch doesn't return an - // error, we need to clean up our internal state to ensure it matches - // inotify's kernel state. - delete(w.paths, int(watch.wd)) - delete(w.watches, name) - - // inotify_rm_watch will return EINVAL if the file has been deleted; - // the inotify will already have been removed. - // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously - // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE - // so that EINVAL means that the wd is being rm_watch()ed or its file removed - // by another thread and we have not received IN_IGNORE event. - success, errno := unix.InotifyRmWatch(w.fd, watch.wd) + success, errno := unix.InotifyRmWatch(w.fd, wd) if success == -1 { // TODO: Perhaps it's not helpful to return an error here in every case; // The only two possible errors are: @@ -312,28 +439,28 @@ func (w *Watcher) Remove(name string) error { // are watching is deleted. return errno } - return nil } -// WatchList returns all paths added with [Add] (and are not yet removed). +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) WatchList() []string { - w.mu.Lock() - defer w.mu.Unlock() + if w.isClosed() { + return nil + } - entries := make([]string, 0, len(w.watches)) - for pathname := range w.watches { + entries := make([]string, 0, w.watches.len()) + w.watches.mu.RLock() + for pathname := range w.watches.path { entries = append(entries, pathname) } + w.watches.mu.RUnlock() return entries } -type watch struct { - wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) - flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) -} - // readEvents reads from the inotify file descriptor, converts the // received events into Event objects and sends them via the Events channel func (w *Watcher) readEvents() { @@ -367,14 +494,11 @@ func (w *Watcher) readEvents() { if n < unix.SizeofInotifyEvent { var err error if n == 0 { - // If EOF is received. This should really never happen. - err = io.EOF + err = io.EOF // If EOF is received. This should really never happen. } else if n < 0 { - // If an error occurred while reading. - err = errno + err = errno // If an error occurred while reading. } else { - // Read was too short. - err = errors.New("notify: short read in readEvents()") + err = errors.New("notify: short read in readEvents()") // Read was too short. } if !w.sendError(err) { return @@ -403,18 +527,29 @@ func (w *Watcher) readEvents() { // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from // the "paths" map. - w.mu.Lock() - name, ok := w.paths[int(raw.Wd)] - // IN_DELETE_SELF occurs when the file/directory being watched is removed. - // This is a sign to clean up the maps, otherwise we are no longer in sync - // with the inotify kernel state which has already deleted the watch - // automatically. - if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { - delete(w.paths, int(raw.Wd)) - delete(w.watches, name) + watch := w.watches.byWd(uint32(raw.Wd)) + + // inotify will automatically remove the watch on deletes; just need + // to clean our state here. + if watch != nil && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { + w.watches.remove(watch.wd) + } + // We can't really update the state when a watched path is moved; + // only IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove + // the watch. + if watch != nil && mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF { + err := w.remove(watch.path) + if err != nil && !errors.Is(err, ErrNonExistentWatch) { + if !w.sendError(err) { + return + } + } } - w.mu.Unlock() + var name string + if watch != nil { + name = watch.path + } if nameLen > 0 { // Point "bytes" at the first byte of the filename bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen] diff --git a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go index 29087469bf..063a0915a0 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go @@ -1,12 +1,14 @@ //go:build freebsd || openbsd || netbsd || dragonfly || darwin // +build freebsd openbsd netbsd dragonfly darwin +// Note: the documentation on the Watcher type and methods is generated from +// mkdoc.zsh + package fsnotify import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "sync" @@ -24,9 +26,9 @@ import ( // When a file is removed a Remove event won't be emitted until all file // descriptors are closed, and deletes will always emit a Chmod. For example: // -// fp := os.Open("file") -// os.Remove("file") // Triggers Chmod -// fp.Close() // Triggers Remove +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove // // This is the event that inotify sends, so not much can be changed about this. // @@ -40,16 +42,16 @@ import ( // // To increase them you can use sysctl or write the value to the /proc file: // -// # Default values on Linux 5.18 -// sysctl fs.inotify.max_user_watches=124983 -// sysctl fs.inotify.max_user_instances=128 +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 // // To make the changes persist on reboot edit /etc/sysctl.conf or // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check // your distro's documentation): // -// fs.inotify.max_user_watches=124983 -// fs.inotify.max_user_instances=128 +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 // // Reaching the limit will result in a "no space left on device" or "too many open // files" error. @@ -65,14 +67,20 @@ import ( // control the maximum number of open files, as well as /etc/login.conf on BSD // systems. // -// # macOS notes +// # Windows notes +// +// Paths can be added as "C:\path\to\dir", but forward slashes +// ("C:/path/to/dir") will also work. // -// Spotlight indexing on macOS can result in multiple events (see [#15]). A -// temporary workaround is to add your folder(s) to the "Spotlight Privacy -// Settings" until we have a native FSEvents implementation (see [#11]). +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all times, sometimes it will send no +// events, and often only for some files. // -// [#11]: https://github.com/fsnotify/fsnotify/issues/11 -// [#15]: https://github.com/fsnotify/fsnotify/issues/15 +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. type Watcher struct { // Events sends the filesystem change events. // @@ -99,18 +107,27 @@ type Watcher struct { // initiated by the user may show up as one or multiple // writes, depending on when the system syncs things to // disk. For example when compiling a large Go program - // you may get hundreds of Write events, so you - // probably want to wait until you've stopped receiving - // them (see the dedup example in cmd/fsnotify). + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. // // fsnotify.Chmod Attributes were changed. On Linux this is also sent // when a file is removed (or more accurately, when a // link to an inode is removed). On kqueue it's sent - // and on kqueue when a file is truncated. On Windows - // it's never sent. + // when a file is truncated. On Windows it's never + // sent. Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. Errors chan error done chan struct{} @@ -133,6 +150,18 @@ type pathInfo struct { // NewWatcher creates a new Watcher. func NewWatcher() (*Watcher, error) { + return NewBufferedWatcher(0) +} + +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { kq, closepipe, err := newKqueue() if err != nil { return nil, err @@ -147,7 +176,7 @@ func NewWatcher() (*Watcher, error) { paths: make(map[int]pathInfo), fileExists: make(map[string]struct{}), userWatches: make(map[string]struct{}), - Events: make(chan Event), + Events: make(chan Event, sz), Errors: make(chan error), done: make(chan struct{}), } @@ -197,8 +226,8 @@ func (w *Watcher) sendEvent(e Event) bool { case w.Events <- e: return true case <-w.done: + return false } - return false } // Returns true if the error was sent, or false if watcher is closed. @@ -207,11 +236,11 @@ func (w *Watcher) sendError(err error) bool { case w.Errors <- err: return true case <-w.done: + return false } - return false } -// Close removes all watches and closes the events channel. +// Close removes all watches and closes the Events channel. func (w *Watcher) Close() error { w.mu.Lock() if w.isClosed { @@ -239,17 +268,21 @@ func (w *Watcher) Close() error { // Add starts monitoring the path for changes. // -// A path can only be watched once; attempting to watch it more than once will -// return an error. Paths that do not yet exist on the filesystem cannot be -// added. A watch will be automatically removed if the path is deleted. +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. // -// A path will remain watched if it gets renamed to somewhere else on the same -// filesystem, but the monitor will get removed if the path gets deleted and -// re-created, or if it's moved to a different filesystem. +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. // // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special // filesystems (/proc, /sys, etc.) generally don't work. // +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// // # Watching directories // // All files in a directory are monitored, including new files that are created @@ -259,15 +292,28 @@ func (w *Watcher) Close() error { // # Watching files // // Watching individual files (rather than directories) is generally not -// recommended as many tools update files atomically. Instead of "just" writing -// to the file a temporary file will be written to first, and if successful the -// temporary file is moved to to destination removing the original, or some -// variant thereof. The watcher on the original file is now lost, as it no -// longer exists. -// -// Instead, watch the parent directory and use Event.Name to filter out files -// you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. -func (w *Watcher) Add(name string) error { +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(name string) error { return w.AddWith(name) } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(name string, opts ...addOpt) error { + _ = getOptions(opts...) + w.mu.Lock() w.userWatches[name] = struct{}{} w.mu.Unlock() @@ -281,9 +327,19 @@ func (w *Watcher) Add(name string) error { // /tmp/dir and /tmp/dir/subdir then you will need to remove both. // // Removing a path that has not yet been added returns [ErrNonExistentWatch]. +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) Remove(name string) error { + return w.remove(name, true) +} + +func (w *Watcher) remove(name string, unwatchFiles bool) error { name = filepath.Clean(name) w.mu.Lock() + if w.isClosed { + w.mu.Unlock() + return nil + } watchfd, ok := w.watches[name] w.mu.Unlock() if !ok { @@ -315,7 +371,7 @@ func (w *Watcher) Remove(name string) error { w.mu.Unlock() // Find all watched paths that are in this directory that are not external. - if isDir { + if unwatchFiles && isDir { var pathsToRemove []string w.mu.Lock() for fd := range w.watchesByDir[name] { @@ -326,20 +382,25 @@ func (w *Watcher) Remove(name string) error { } w.mu.Unlock() for _, name := range pathsToRemove { - // Since these are internal, not much sense in propagating error - // to the user, as that will just confuse them with an error about - // a path they did not explicitly watch themselves. + // Since these are internal, not much sense in propagating error to + // the user, as that will just confuse them with an error about a + // path they did not explicitly watch themselves. w.Remove(name) } } - return nil } -// WatchList returns all paths added with [Add] (and are not yet removed). +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) WatchList() []string { w.mu.Lock() defer w.mu.Unlock() + if w.isClosed { + return nil + } entries := make([]string, 0, len(w.userWatches)) for pathname := range w.userWatches { @@ -352,18 +413,18 @@ func (w *Watcher) WatchList() []string { // Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME -// addWatch adds name to the watched file set. -// The flags are interpreted as described in kevent(2). -// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks. +// addWatch adds name to the watched file set; the flags are interpreted as +// described in kevent(2). +// +// Returns the real path to the file which was added, with symlinks resolved. func (w *Watcher) addWatch(name string, flags uint32) (string, error) { var isDir bool - // Make ./name and name equivalent name = filepath.Clean(name) w.mu.Lock() if w.isClosed { w.mu.Unlock() - return "", errors.New("kevent instance already closed") + return "", ErrClosed } watchfd, alreadyWatching := w.watches[name] // We already have a watch, but we can still override flags. @@ -383,27 +444,30 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) { return "", nil } - // Follow Symlinks - // - // Linux can add unresolvable symlinks to the watch list without issue, - // and Windows can't do symlinks period. To maintain consistency, we - // will act like everything is fine if the link can't be resolved. - // There will simply be no file events for broken symlinks. Hence the - // returns of nil on errors. + // Follow Symlinks. if fi.Mode()&os.ModeSymlink == os.ModeSymlink { - name, err = filepath.EvalSymlinks(name) + link, err := os.Readlink(name) if err != nil { + // Return nil because Linux can add unresolvable symlinks to the + // watch list without problems, so maintain consistency with + // that. There will be no file events for broken symlinks. + // TODO: more specific check; returns os.PathError; ENOENT? return "", nil } w.mu.Lock() - _, alreadyWatching = w.watches[name] + _, alreadyWatching = w.watches[link] w.mu.Unlock() if alreadyWatching { - return name, nil + // Add to watches so we don't get spurious Create events later + // on when we diff the directories. + w.watches[name] = 0 + w.fileExists[name] = struct{}{} + return link, nil } + name = link fi, err = os.Lstat(name) if err != nil { return "", nil @@ -411,7 +475,7 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) { } // Retry on EINTR; open() can return EINTR in practice on macOS. - // See #354, and go issues 11180 and 39237. + // See #354, and Go issues 11180 and 39237. for { watchfd, err = unix.Open(name, openMode, 0) if err == nil { @@ -444,14 +508,13 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) { w.watchesByDir[parentName] = watchesByDir } watchesByDir[watchfd] = struct{}{} - w.paths[watchfd] = pathInfo{name: name, isDir: isDir} w.mu.Unlock() } if isDir { - // Watch the directory if it has not been watched before, - // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) + // Watch the directory if it has not been watched before, or if it was + // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) w.mu.Lock() watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && @@ -473,13 +536,10 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) { // Event values that it sends down the Events channel. func (w *Watcher) readEvents() { defer func() { - err := unix.Close(w.kq) - if err != nil { - w.Errors <- err - } - unix.Close(w.closepipe[0]) close(w.Events) close(w.Errors) + _ = unix.Close(w.kq) + unix.Close(w.closepipe[0]) }() eventBuffer := make([]unix.Kevent_t, 10) @@ -513,18 +573,8 @@ func (w *Watcher) readEvents() { event := w.newEvent(path.name, mask) - if path.isDir && !event.Has(Remove) { - // Double check to make sure the directory exists. This can - // happen when we do a rm -fr on a recursively watched folders - // and we receive a modification event first but the folder has - // been deleted and later receive the delete event. - if _, err := os.Lstat(event.Name); os.IsNotExist(err) { - event.Op |= Remove - } - } - if event.Has(Rename) || event.Has(Remove) { - w.Remove(event.Name) + w.remove(event.Name, false) w.mu.Lock() delete(w.fileExists, event.Name) w.mu.Unlock() @@ -540,26 +590,30 @@ func (w *Watcher) readEvents() { } if event.Has(Remove) { - // Look for a file that may have overwritten this. - // For example, mv f1 f2 will delete f2, then create f2. + // Look for a file that may have overwritten this; for example, + // mv f1 f2 will delete f2, then create f2. if path.isDir { fileDir := filepath.Clean(event.Name) w.mu.Lock() _, found := w.watches[fileDir] w.mu.Unlock() if found { - // make sure the directory exists before we watch for changes. When we - // do a recursive watch and perform rm -fr, the parent directory might - // have gone missing, ignore the missing directory and let the - // upcoming delete event remove the watch from the parent directory. - if _, err := os.Lstat(fileDir); err == nil { - w.sendDirectoryChangeEvents(fileDir) + err := w.sendDirectoryChangeEvents(fileDir) + if err != nil { + if !w.sendError(err) { + closed = true + } } } } else { filePath := filepath.Clean(event.Name) - if fileInfo, err := os.Lstat(filePath); err == nil { - w.sendFileCreatedEventIfNew(filePath, fileInfo) + if fi, err := os.Lstat(filePath); err == nil { + err := w.sendFileCreatedEventIfNew(filePath, fi) + if err != nil { + if !w.sendError(err) { + closed = true + } + } } } } @@ -582,21 +636,31 @@ func (w *Watcher) newEvent(name string, mask uint32) Event { if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { e.Op |= Chmod } + // No point sending a write and delete event at the same time: if it's gone, + // then it's gone. + if e.Op.Has(Write) && e.Op.Has(Remove) { + e.Op &^= Write + } return e } // watchDirectoryFiles to mimic inotify when adding a watch on a directory func (w *Watcher) watchDirectoryFiles(dirPath string) error { // Get all files - files, err := ioutil.ReadDir(dirPath) + files, err := os.ReadDir(dirPath) if err != nil { return err } - for _, fileInfo := range files { - path := filepath.Join(dirPath, fileInfo.Name()) + for _, f := range files { + path := filepath.Join(dirPath, f.Name()) + + fi, err := f.Info() + if err != nil { + return fmt.Errorf("%q: %w", path, err) + } - cleanPath, err := w.internalWatch(path, fileInfo) + cleanPath, err := w.internalWatch(path, fi) if err != nil { // No permission to read the file; that's not a problem: just skip. // But do add it to w.fileExists to prevent it from being picked up @@ -606,7 +670,7 @@ func (w *Watcher) watchDirectoryFiles(dirPath string) error { case errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM): cleanPath = filepath.Clean(path) default: - return fmt.Errorf("%q: %w", filepath.Join(dirPath, fileInfo.Name()), err) + return fmt.Errorf("%q: %w", path, err) } } @@ -622,26 +686,37 @@ func (w *Watcher) watchDirectoryFiles(dirPath string) error { // // This functionality is to have the BSD watcher match the inotify, which sends // a create event for files created in a watched directory. -func (w *Watcher) sendDirectoryChangeEvents(dir string) { - // Get all files - files, err := ioutil.ReadDir(dir) +func (w *Watcher) sendDirectoryChangeEvents(dir string) error { + files, err := os.ReadDir(dir) if err != nil { - if !w.sendError(fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err)) { - return + // Directory no longer exists: we can ignore this safely. kqueue will + // still give us the correct events. + if errors.Is(err, os.ErrNotExist) { + return nil } + return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err) } - // Search for new files - for _, fi := range files { - err := w.sendFileCreatedEventIfNew(filepath.Join(dir, fi.Name()), fi) + for _, f := range files { + fi, err := f.Info() if err != nil { - return + return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err) + } + + err = w.sendFileCreatedEventIfNew(filepath.Join(dir, fi.Name()), fi) + if err != nil { + // Don't need to send an error if this file isn't readable. + if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) { + return nil + } + return fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err) } } + return nil } // sendFileCreatedEvent sends a create event if the file isn't already being tracked. -func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) { +func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fi os.FileInfo) (err error) { w.mu.Lock() _, doesExist := w.fileExists[filePath] w.mu.Unlock() @@ -652,7 +727,7 @@ func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInf } // like watchDirectoryFiles (but without doing another ReadDir) - filePath, err = w.internalWatch(filePath, fileInfo) + filePath, err = w.internalWatch(filePath, fi) if err != nil { return err } @@ -664,10 +739,10 @@ func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInf return nil } -func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) { - if fileInfo.IsDir() { - // mimic Linux providing delete events for subdirectories - // but preserve the flags used if currently watching subdirectory +func (w *Watcher) internalWatch(name string, fi os.FileInfo) (string, error) { + if fi.IsDir() { + // mimic Linux providing delete events for subdirectories, but preserve + // the flags used if currently watching subdirectory w.mu.Lock() flags := w.dirFlags[name] w.mu.Unlock() diff --git a/vendor/github.com/fsnotify/fsnotify/backend_other.go b/vendor/github.com/fsnotify/fsnotify/backend_other.go index a9bb1c3c4d..d34a23c015 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_other.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_other.go @@ -1,39 +1,169 @@ -//go:build !darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows -// +build !darwin,!dragonfly,!freebsd,!openbsd,!linux,!netbsd,!solaris,!windows +//go:build appengine || (!darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows) +// +build appengine !darwin,!dragonfly,!freebsd,!openbsd,!linux,!netbsd,!solaris,!windows + +// Note: the documentation on the Watcher type and methods is generated from +// mkdoc.zsh package fsnotify -import ( - "fmt" - "runtime" -) +import "errors" -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct{} +// Watcher watches a set of paths, delivering events on a channel. +// +// A watcher should not be copied (e.g. pass it by pointer, rather than by +// value). +// +// # Linux notes +// +// When a file is removed a Remove event won't be emitted until all file +// descriptors are closed, and deletes will always emit a Chmod. For example: +// +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove +// +// This is the event that inotify sends, so not much can be changed about this. +// +// The fs.inotify.max_user_watches sysctl variable specifies the upper limit +// for the number of watches per user, and fs.inotify.max_user_instances +// specifies the maximum number of inotify instances per user. Every Watcher you +// create is an "instance", and every path you add is a "watch". +// +// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and +// /proc/sys/fs/inotify/max_user_instances +// +// To increase them you can use sysctl or write the value to the /proc file: +// +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 +// +// To make the changes persist on reboot edit /etc/sysctl.conf or +// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check +// your distro's documentation): +// +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 +// +// Reaching the limit will result in a "no space left on device" or "too many open +// files" error. +// +// # kqueue notes (macOS, BSD) +// +// kqueue requires opening a file descriptor for every file that's being watched; +// so if you're watching a directory with five files then that's six file +// descriptors. You will run in to your system's "max open files" limit faster on +// these platforms. +// +// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to +// control the maximum number of open files, as well as /etc/login.conf on BSD +// systems. +// +// # Windows notes +// +// Paths can be added as "C:\path\to\dir", but forward slashes +// ("C:/path/to/dir") will also work. +// +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all times, sometimes it will send no +// events, and often only for some files. +// +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. +type Watcher struct { + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event + + // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + Errors chan error +} // NewWatcher creates a new Watcher. func NewWatcher() (*Watcher, error) { - return nil, fmt.Errorf("fsnotify not supported on %s", runtime.GOOS) + return nil, errors.New("fsnotify not supported on the current platform") } -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - return nil -} +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { return NewWatcher() } + +// Close removes all watches and closes the Events channel. +func (w *Watcher) Close() error { return nil } + +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// Returns nil if [Watcher.Close] was called. +func (w *Watcher) WatchList() []string { return nil } // Add starts monitoring the path for changes. // -// A path can only be watched once; attempting to watch it more than once will -// return an error. Paths that do not yet exist on the filesystem cannot be -// added. A watch will be automatically removed if the path is deleted. +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. // -// A path will remain watched if it gets renamed to somewhere else on the same -// filesystem, but the monitor will get removed if the path gets deleted and -// re-created, or if it's moved to a different filesystem. +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. // // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special // filesystems (/proc, /sys, etc.) generally don't work. // +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// // # Watching directories // // All files in a directory are monitored, including new files that are created @@ -43,17 +173,26 @@ func (w *Watcher) Close() error { // # Watching files // // Watching individual files (rather than directories) is generally not -// recommended as many tools update files atomically. Instead of "just" writing -// to the file a temporary file will be written to first, and if successful the -// temporary file is moved to to destination removing the original, or some -// variant thereof. The watcher on the original file is now lost, as it no -// longer exists. -// -// Instead, watch the parent directory and use Event.Name to filter out files -// you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. -func (w *Watcher) Add(name string) error { - return nil -} +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(name string) error { return nil } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(name string, opts ...addOpt) error { return nil } // Remove stops monitoring the path for changes. // @@ -61,6 +200,6 @@ func (w *Watcher) Add(name string) error { // /tmp/dir and /tmp/dir/subdir then you will need to remove both. // // Removing a path that has not yet been added returns [ErrNonExistentWatch]. -func (w *Watcher) Remove(name string) error { - return nil -} +// +// Returns nil if [Watcher.Close] was called. +func (w *Watcher) Remove(name string) error { return nil } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_windows.go b/vendor/github.com/fsnotify/fsnotify/backend_windows.go index ae392867c0..9bc91e5d61 100644 --- a/vendor/github.com/fsnotify/fsnotify/backend_windows.go +++ b/vendor/github.com/fsnotify/fsnotify/backend_windows.go @@ -1,6 +1,13 @@ //go:build windows // +build windows +// Windows backend based on ReadDirectoryChangesW() +// +// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw +// +// Note: the documentation on the Watcher type and methods is generated from +// mkdoc.zsh + package fsnotify import ( @@ -27,9 +34,9 @@ import ( // When a file is removed a Remove event won't be emitted until all file // descriptors are closed, and deletes will always emit a Chmod. For example: // -// fp := os.Open("file") -// os.Remove("file") // Triggers Chmod -// fp.Close() // Triggers Remove +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove // // This is the event that inotify sends, so not much can be changed about this. // @@ -43,16 +50,16 @@ import ( // // To increase them you can use sysctl or write the value to the /proc file: // -// # Default values on Linux 5.18 -// sysctl fs.inotify.max_user_watches=124983 -// sysctl fs.inotify.max_user_instances=128 +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 // // To make the changes persist on reboot edit /etc/sysctl.conf or // /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check // your distro's documentation): // -// fs.inotify.max_user_watches=124983 -// fs.inotify.max_user_instances=128 +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 // // Reaching the limit will result in a "no space left on device" or "too many open // files" error. @@ -68,14 +75,20 @@ import ( // control the maximum number of open files, as well as /etc/login.conf on BSD // systems. // -// # macOS notes +// # Windows notes // -// Spotlight indexing on macOS can result in multiple events (see [#15]). A -// temporary workaround is to add your folder(s) to the "Spotlight Privacy -// Settings" until we have a native FSEvents implementation (see [#11]). +// Paths can be added as "C:\path\to\dir", but forward slashes +// ("C:/path/to/dir") will also work. // -// [#11]: https://github.com/fsnotify/fsnotify/issues/11 -// [#15]: https://github.com/fsnotify/fsnotify/issues/15 +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all times, sometimes it will send no +// events, and often only for some files. +// +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. type Watcher struct { // Events sends the filesystem change events. // @@ -102,31 +115,52 @@ type Watcher struct { // initiated by the user may show up as one or multiple // writes, depending on when the system syncs things to // disk. For example when compiling a large Go program - // you may get hundreds of Write events, so you - // probably want to wait until you've stopped receiving - // them (see the dedup example in cmd/fsnotify). + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. // // fsnotify.Chmod Attributes were changed. On Linux this is also sent // when a file is removed (or more accurately, when a // link to an inode is removed). On kqueue it's sent - // and on kqueue when a file is truncated. On Windows - // it's never sent. + // when a file is truncated. On Windows it's never + // sent. Events chan Event // Errors sends any errors. + // + // ErrEventOverflow is used to indicate there are too many events: + // + // - inotify: There are too many queued events (fs.inotify.max_queued_events sysctl) + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. Errors chan error port windows.Handle // Handle to completion port input chan *input // Inputs to the reader are sent on this channel quit chan chan<- error - mu sync.Mutex // Protects access to watches, isClosed - watches watchMap // Map of watches (key: i-number) - isClosed bool // Set to true when Close() is first called + mu sync.Mutex // Protects access to watches, closed + watches watchMap // Map of watches (key: i-number) + closed bool // Set to true when Close() is first called } // NewWatcher creates a new Watcher. func NewWatcher() (*Watcher, error) { + return NewBufferedWatcher(50) +} + +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0) if err != nil { return nil, os.NewSyscallError("CreateIoCompletionPort", err) @@ -135,7 +169,7 @@ func NewWatcher() (*Watcher, error) { port: port, watches: make(watchMap), input: make(chan *input, 1), - Events: make(chan Event, 50), + Events: make(chan Event, sz), Errors: make(chan error), quit: make(chan chan<- error, 1), } @@ -143,6 +177,12 @@ func NewWatcher() (*Watcher, error) { return w, nil } +func (w *Watcher) isClosed() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.closed +} + func (w *Watcher) sendEvent(name string, mask uint64) bool { if mask == 0 { return false @@ -167,14 +207,14 @@ func (w *Watcher) sendError(err error) bool { return false } -// Close removes all watches and closes the events channel. +// Close removes all watches and closes the Events channel. func (w *Watcher) Close() error { - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() + if w.isClosed() { return nil } - w.isClosed = true + + w.mu.Lock() + w.closed = true w.mu.Unlock() // Send "quit" message to the reader goroutine @@ -188,17 +228,21 @@ func (w *Watcher) Close() error { // Add starts monitoring the path for changes. // -// A path can only be watched once; attempting to watch it more than once will -// return an error. Paths that do not yet exist on the filesystem cannot be -// added. A watch will be automatically removed if the path is deleted. +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. // -// A path will remain watched if it gets renamed to somewhere else on the same -// filesystem, but the monitor will get removed if the path gets deleted and -// re-created, or if it's moved to a different filesystem. +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. // // Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special // filesystems (/proc, /sys, etc.) generally don't work. // +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// // # Watching directories // // All files in a directory are monitored, including new files that are created @@ -208,27 +252,41 @@ func (w *Watcher) Close() error { // # Watching files // // Watching individual files (rather than directories) is generally not -// recommended as many tools update files atomically. Instead of "just" writing -// to the file a temporary file will be written to first, and if successful the -// temporary file is moved to to destination removing the original, or some -// variant thereof. The watcher on the original file is now lost, as it no -// longer exists. -// -// Instead, watch the parent directory and use Event.Name to filter out files -// you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. -func (w *Watcher) Add(name string) error { - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return errors.New("watcher already closed") +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(name string) error { return w.AddWith(name) } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + + with := getOptions(opts...) + if with.bufsize < 4096 { + return fmt.Errorf("fsnotify.WithBufferSize: buffer size cannot be smaller than 4096 bytes") } - w.mu.Unlock() in := &input{ - op: opAddWatch, - path: filepath.Clean(name), - flags: sysFSALLEVENTS, - reply: make(chan error), + op: opAddWatch, + path: filepath.Clean(name), + flags: sysFSALLEVENTS, + reply: make(chan error), + bufsize: with.bufsize, } w.input <- in if err := w.wakeupReader(); err != nil { @@ -243,7 +301,13 @@ func (w *Watcher) Add(name string) error { // /tmp/dir and /tmp/dir/subdir then you will need to remove both. // // Removing a path that has not yet been added returns [ErrNonExistentWatch]. +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) Remove(name string) error { + if w.isClosed() { + return nil + } + in := &input{ op: opRemoveWatch, path: filepath.Clean(name), @@ -256,8 +320,15 @@ func (w *Watcher) Remove(name string) error { return <-in.reply } -// WatchList returns all paths added with [Add] (and are not yet removed). +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// Returns nil if [Watcher.Close] was called. func (w *Watcher) WatchList() []string { + if w.isClosed() { + return nil + } + w.mu.Lock() defer w.mu.Unlock() @@ -279,7 +350,6 @@ func (w *Watcher) WatchList() []string { // This should all be removed at some point, and just use windows.FILE_NOTIFY_* const ( sysFSALLEVENTS = 0xfff - sysFSATTRIB = 0x4 sysFSCREATE = 0x100 sysFSDELETE = 0x200 sysFSDELETESELF = 0x400 @@ -305,9 +375,6 @@ func (w *Watcher) newEvent(name string, mask uint32) Event { if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { e.Op |= Rename } - if mask&sysFSATTRIB == sysFSATTRIB { - e.Op |= Chmod - } return e } @@ -321,10 +388,11 @@ const ( ) type input struct { - op int - path string - flags uint32 - reply chan error + op int + path string + flags uint32 + bufsize int + reply chan error } type inode struct { @@ -334,13 +402,14 @@ type inode struct { } type watch struct { - ov windows.Overlapped - ino *inode // i-number - path string // Directory path - mask uint64 // Directory itself is being watched with these notify flags - names map[string]uint64 // Map of names being watched and their notify flags - rename string // Remembers the old name while renaming a file - buf [65536]byte // 64K buffer + ov windows.Overlapped + ino *inode // i-number + recurse bool // Recursive watch? + path string // Directory path + mask uint64 // Directory itself is being watched with these notify flags + names map[string]uint64 // Map of names being watched and their notify flags + rename string // Remembers the old name while renaming a file + buf []byte // buffer, allocated later } type ( @@ -413,7 +482,10 @@ func (m watchMap) set(ino *inode, watch *watch) { } // Must run within the I/O thread. -func (w *Watcher) addWatch(pathname string, flags uint64) error { +func (w *Watcher) addWatch(pathname string, flags uint64, bufsize int) error { + //pathname, recurse := recursivePath(pathname) + recurse := false + dir, err := w.getDir(pathname) if err != nil { return err @@ -433,9 +505,11 @@ func (w *Watcher) addWatch(pathname string, flags uint64) error { return os.NewSyscallError("CreateIoCompletionPort", err) } watchEntry = &watch{ - ino: ino, - path: dir, - names: make(map[string]uint64), + ino: ino, + path: dir, + names: make(map[string]uint64), + recurse: recurse, + buf: make([]byte, bufsize), } w.mu.Lock() w.watches.set(ino, watchEntry) @@ -465,6 +539,8 @@ func (w *Watcher) addWatch(pathname string, flags uint64) error { // Must run within the I/O thread. func (w *Watcher) remWatch(pathname string) error { + pathname, recurse := recursivePath(pathname) + dir, err := w.getDir(pathname) if err != nil { return err @@ -478,6 +554,10 @@ func (w *Watcher) remWatch(pathname string) error { watch := w.watches.get(ino) w.mu.Unlock() + if recurse && !watch.recurse { + return fmt.Errorf("can't use \\... with non-recursive watch %q", pathname) + } + err = windows.CloseHandle(ino.handle) if err != nil { w.sendError(os.NewSyscallError("CloseHandle", err)) @@ -535,8 +615,11 @@ func (w *Watcher) startRead(watch *watch) error { return nil } - rdErr := windows.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0], - uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0) + // We need to pass the array, rather than the slice. + hdr := (*reflect.SliceHeader)(unsafe.Pointer(&watch.buf)) + rdErr := windows.ReadDirectoryChanges(watch.ino.handle, + (*byte)(unsafe.Pointer(hdr.Data)), uint32(hdr.Len), + watch.recurse, mask, nil, &watch.ov, 0) if rdErr != nil { err := os.NewSyscallError("ReadDirectoryChanges", rdErr) if rdErr == windows.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { @@ -563,9 +646,8 @@ func (w *Watcher) readEvents() { runtime.LockOSThread() for { + // This error is handled after the watch == nil check below. qErr := windows.GetQueuedCompletionStatus(w.port, &n, &key, &ov, windows.INFINITE) - // This error is handled after the watch == nil check below. NOTE: this - // seems odd, note sure if it's correct. watch := (*watch)(unsafe.Pointer(ov)) if watch == nil { @@ -595,7 +677,7 @@ func (w *Watcher) readEvents() { case in := <-w.input: switch in.op { case opAddWatch: - in.reply <- w.addWatch(in.path, uint64(in.flags)) + in.reply <- w.addWatch(in.path, uint64(in.flags), in.bufsize) case opRemoveWatch: in.reply <- w.remWatch(in.path) } @@ -605,6 +687,8 @@ func (w *Watcher) readEvents() { } switch qErr { + case nil: + // No error case windows.ERROR_MORE_DATA: if watch == nil { w.sendError(errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")) @@ -626,13 +710,12 @@ func (w *Watcher) readEvents() { default: w.sendError(os.NewSyscallError("GetQueuedCompletionPort", qErr)) continue - case nil: } var offset uint32 for { if n == 0 { - w.sendError(errors.New("short read in readEvents()")) + w.sendError(ErrEventOverflow) break } @@ -703,8 +786,9 @@ func (w *Watcher) readEvents() { // Error! if offset >= n { + //lint:ignore ST1005 Windows should be capitalized w.sendError(errors.New( - "Windows system assumed buffer larger than it is, events have likely been missed.")) + "Windows system assumed buffer larger than it is, events have likely been missed")) break } } @@ -720,9 +804,6 @@ func (w *Watcher) toWindowsFlags(mask uint64) uint32 { if mask&sysFSMODIFY != 0 { m |= windows.FILE_NOTIFY_CHANGE_LAST_WRITE } - if mask&sysFSATTRIB != 0 { - m |= windows.FILE_NOTIFY_CHANGE_ATTRIBUTES - } if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { m |= windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME } diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go index 30a5bf0f07..24c99cc499 100644 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -1,13 +1,18 @@ -//go:build !plan9 -// +build !plan9 - // Package fsnotify provides a cross-platform interface for file system // notifications. +// +// Currently supported systems: +// +// Linux 2.6.32+ via inotify +// BSD, macOS via kqueue +// Windows via ReadDirectoryChangesW +// illumos via FEN package fsnotify import ( "errors" "fmt" + "path/filepath" "strings" ) @@ -33,34 +38,52 @@ type Op uint32 // The operations fsnotify can trigger; see the documentation on [Watcher] for a // full description, and check them with [Event.Has]. const ( + // A new pathname was created. Create Op = 1 << iota + + // The pathname was written to; this does *not* mean the write has finished, + // and a write can be followed by more writes. Write + + // The path was removed; any watches on it will be removed. Some "remove" + // operations may trigger a Rename if the file is actually moved (for + // example "remove to trash" is often a rename). Remove + + // The path was renamed to something else; any watched on it will be + // removed. Rename + + // File attributes were changed. + // + // It's generally not recommended to take action on this event, as it may + // get triggered very frequently by some software. For example, Spotlight + // indexing on macOS, anti-virus software, backup software, etc. Chmod ) -// Common errors that can be reported by a watcher +// Common errors that can be reported. var ( - ErrNonExistentWatch = errors.New("can't remove non-existent watcher") - ErrEventOverflow = errors.New("fsnotify queue overflow") + ErrNonExistentWatch = errors.New("fsnotify: can't remove non-existent watch") + ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow") + ErrClosed = errors.New("fsnotify: watcher already closed") ) -func (op Op) String() string { +func (o Op) String() string { var b strings.Builder - if op.Has(Create) { + if o.Has(Create) { b.WriteString("|CREATE") } - if op.Has(Remove) { + if o.Has(Remove) { b.WriteString("|REMOVE") } - if op.Has(Write) { + if o.Has(Write) { b.WriteString("|WRITE") } - if op.Has(Rename) { + if o.Has(Rename) { b.WriteString("|RENAME") } - if op.Has(Chmod) { + if o.Has(Chmod) { b.WriteString("|CHMOD") } if b.Len() == 0 { @@ -70,7 +93,7 @@ func (op Op) String() string { } // Has reports if this operation has the given operation. -func (o Op) Has(h Op) bool { return o&h == h } +func (o Op) Has(h Op) bool { return o&h != 0 } // Has reports if this event has the given operation. func (e Event) Has(op Op) bool { return e.Op.Has(op) } @@ -79,3 +102,45 @@ func (e Event) Has(op Op) bool { return e.Op.Has(op) } func (e Event) String() string { return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name) } + +type ( + addOpt func(opt *withOpts) + withOpts struct { + bufsize int + } +) + +var defaultOpts = withOpts{ + bufsize: 65536, // 64K +} + +func getOptions(opts ...addOpt) withOpts { + with := defaultOpts + for _, o := range opts { + o(&with) + } + return with +} + +// WithBufferSize sets the [ReadDirectoryChangesW] buffer size. +// +// This only has effect on Windows systems, and is a no-op for other backends. +// +// The default value is 64K (65536 bytes) which is the highest value that works +// on all filesystems and should be enough for most applications, but if you +// have a large burst of events it may not be enough. You can increase it if +// you're hitting "queue or buffer overflow" errors ([ErrEventOverflow]). +// +// [ReadDirectoryChangesW]: https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-readdirectorychangesw +func WithBufferSize(bytes int) addOpt { + return func(opt *withOpts) { opt.bufsize = bytes } +} + +// Check if this path is recursive (ends with "/..." or "\..."), and return the +// path with the /... stripped. +func recursivePath(path string) (string, bool) { + if filepath.Base(path) == "..." { + return filepath.Dir(path), true + } + return path, false +} diff --git a/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh b/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh index b09ef76834..99012ae653 100644 --- a/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh +++ b/vendor/github.com/fsnotify/fsnotify/mkdoc.zsh @@ -2,8 +2,8 @@ [ "${ZSH_VERSION:-}" = "" ] && echo >&2 "Only works with zsh" && exit 1 setopt err_exit no_unset pipefail extended_glob -# Simple script to update the godoc comments on all watchers. Probably took me -# more time to write this than doing it manually, but ah well 🙃 +# Simple script to update the godoc comments on all watchers so you don't need +# to update the same comment 5 times. watcher=$(<=", 17)) }, SpecTimeout(time.Second)) -you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with paseed-in arguments as long as the context appears first. You can rewrite the above example as: +you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with passed-in arguments as long as the context appears first. You can rewrite the above example as: It("fetches the correct count", func(ctx SpecContext) { Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) -Either way the context passd to Eventually is also passed to the underlying funciton. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. +Either way the context passd to Eventually is also passed to the underlying function. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. **Category 3: Making assertions _in_ the function passed into Eventually** @@ -349,7 +349,7 @@ For example: will rerun the function until all assertions pass. -You can also pass additional arugments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example: +You can also pass additional arguments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example: Eventually(func(g Gomega, ctx context.Context, path string, expected ...string){ tok, err := client.GetToken(ctx) diff --git a/vendor/github.com/onsi/gomega/matchers.go b/vendor/github.com/onsi/gomega/matchers.go index 4c13ad0a7b..43f994374d 100644 --- a/vendor/github.com/onsi/gomega/matchers.go +++ b/vendor/github.com/onsi/gomega/matchers.go @@ -1,6 +1,7 @@ package gomega import ( + "fmt" "time" "github.com/google/go-cmp/cmp" @@ -52,15 +53,31 @@ func BeNil() types.GomegaMatcher { } // BeTrue succeeds if actual is true +// +// In general, it's better to use `BeTrueBecause(reason)` to provide a more useful error message if a true check fails. func BeTrue() types.GomegaMatcher { return &matchers.BeTrueMatcher{} } // BeFalse succeeds if actual is false +// +// In general, it's better to use `BeFalseBecause(reason)` to provide a more useful error message if a false check fails. func BeFalse() types.GomegaMatcher { return &matchers.BeFalseMatcher{} } +// BeTrueBecause succeeds if actual is true and displays the provided reason if it is false +// fmt.Sprintf is used to render the reason +func BeTrueBecause(format string, args ...any) types.GomegaMatcher { + return &matchers.BeTrueMatcher{Reason: fmt.Sprintf(format, args...)} +} + +// BeFalseBecause succeeds if actual is false and displays the provided reason if it is true. +// fmt.Sprintf is used to render the reason +func BeFalseBecause(format string, args ...any) types.GomegaMatcher { + return &matchers.BeFalseMatcher{Reason: fmt.Sprintf(format, args...)} +} + // HaveOccurred succeeds if actual is a non-nil error // The typical Go error checking pattern looks like: // @@ -88,19 +105,44 @@ func Succeed() types.GomegaMatcher { } // MatchError succeeds if actual is a non-nil error that matches the passed in -// string, error, or matcher. +// string, error, function, or matcher. // // These are valid use-cases: // -// Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error" -// Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual) -// Expect(err).Should(MatchError(ContainSubstring("sprocket not found"))) // asserts that err.Error() contains substring "sprocket not found" +// When passed a string: +// +// Expect(err).To(MatchError("an error")) +// +// asserts that err.Error() == "an error" +// +// When passed an error: +// +// Expect(err).To(MatchError(SomeError)) +// +// First checks if errors.Is(err, SomeError). +// If that fails then it checks if reflect.DeepEqual(err, SomeError) repeatedly for err and any errors wrapped by err +// +// When passed a matcher: +// +// Expect(err).To(MatchError(ContainSubstring("sprocket not found"))) +// +// the matcher is passed err.Error(). In this case it asserts that err.Error() contains substring "sprocket not found" +// +// When passed a func(err) bool and a description: +// +// Expect(err).To(MatchError(os.IsNotExist, "IsNotExist")) +// +// the function is passed err and matches if the return value is true. The description is required to allow Gomega +// to print a useful error message. // // It is an error for err to be nil or an object that does not implement the // Error interface -func MatchError(expected interface{}) types.GomegaMatcher { +// +// The optional second argument is a description of the error function, if used. This is required when passing a function but is ignored in all other cases. +func MatchError(expected interface{}, functionErrorDescription ...any) types.GomegaMatcher { return &matchers.MatchErrorMatcher{ - Expected: expected, + Expected: expected, + FuncErrDescription: functionErrorDescription, } } @@ -381,7 +423,7 @@ func ContainElements(elements ...interface{}) types.GomegaMatcher { } // HaveEach succeeds if actual solely contains elements that match the passed in element. -// Please note that if actual is empty, HaveEach always will succeed. +// Please note that if actual is empty, HaveEach always will fail. // By default HaveEach() uses Equal() to perform the match, however a // matcher can be passed in instead: // diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go index e326c01577..8ee2b1c51e 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go @@ -9,6 +9,7 @@ import ( ) type BeFalseMatcher struct { + Reason string } func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err error) { @@ -20,9 +21,17 @@ func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err erro } func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be false") + if matcher.Reason == "" { + return format.Message(actual, "to be false") + } else { + return matcher.Reason + } } func (matcher *BeFalseMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be false") + if matcher.Reason == "" { + return format.Message(actual, "not to be false") + } else { + return fmt.Sprintf(`Expected not false but got false\nNegation of "%s" failed`, matcher.Reason) + } } diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go index 60bc1e3fa7..3576aac884 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go @@ -9,6 +9,7 @@ import ( ) type BeTrueMatcher struct { + Reason string } func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error) { @@ -20,9 +21,17 @@ func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error } func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be true") + if matcher.Reason == "" { + return format.Message(actual, "to be true") + } else { + return matcher.Reason + } } func (matcher *BeTrueMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be true") + if matcher.Reason == "" { + return format.Message(actual, "not to be true") + } else { + return fmt.Sprintf(`Expected not true but got true\nNegation of "%s" failed`, matcher.Reason) + } } diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go index 827475ea51..c539dd389c 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go @@ -9,10 +9,14 @@ import ( ) type MatchErrorMatcher struct { - Expected interface{} + Expected any + FuncErrDescription []any + isFunc bool } -func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *MatchErrorMatcher) Match(actual any) (success bool, err error) { + matcher.isFunc = false + if isNil(actual) { return false, fmt.Errorf("Expected an error, got nil") } @@ -42,6 +46,17 @@ func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err e return actualErr.Error() == expected, nil } + v := reflect.ValueOf(expected) + t := v.Type() + errorInterface := reflect.TypeOf((*error)(nil)).Elem() + if t.Kind() == reflect.Func && t.NumIn() == 1 && t.In(0).Implements(errorInterface) && t.NumOut() == 1 && t.Out(0).Kind() == reflect.Bool { + if len(matcher.FuncErrDescription) == 0 { + return false, fmt.Errorf("MatchError requires an additional description when passed a function") + } + matcher.isFunc = true + return v.Call([]reflect.Value{reflect.ValueOf(actualErr)})[0].Bool(), nil + } + var subMatcher omegaMatcher var hasSubMatcher bool if expected != nil { @@ -57,9 +72,15 @@ func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err e } func (matcher *MatchErrorMatcher) FailureMessage(actual interface{}) (message string) { + if matcher.isFunc { + return format.Message(actual, fmt.Sprintf("to match error function %s", matcher.FuncErrDescription[0])) + } return format.Message(actual, "to match error", matcher.Expected) } func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) { + if matcher.isFunc { + return format.Message(actual, fmt.Sprintf("not to match error function %s", matcher.FuncErrDescription[0])) + } return format.Message(actual, "not to match error", matcher.Expected) } diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml index 2578d94b5e..a618ec24d8 100644 --- a/vendor/github.com/spf13/cobra/.golangci.yml +++ b/vendor/github.com/spf13/cobra/.golangci.yml @@ -19,7 +19,7 @@ linters: disable-all: true enable: #- bodyclose - - deadcode + # - deadcode ! deprecated since v1.49.0; replaced by 'unused' #- depguard #- dogsled #- dupl @@ -51,12 +51,12 @@ linters: #- rowserrcheck #- scopelint #- staticcheck - - structcheck + #- structcheck ! deprecated since v1.49.0; replaced by 'unused' #- stylecheck #- typecheck - unconvert #- unparam - #- unused - - varcheck + - unused + # - varcheck ! deprecated since v1.49.0; replaced by 'unused' #- whitespace fast: false diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index 592c0b8ab0..6444f4b7f6 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -4,7 +4,7 @@ Cobra is a library for creating powerful modern CLI applications. Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), [Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to -name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. +name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. [![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) [![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) @@ -80,7 +80,7 @@ which maintains the same interface while adding POSIX compliance. # Installing Using Cobra is easy. First, use `go get` to install the latest version -of the library. +of the library. ``` go get -u github.com/spf13/cobra@latest @@ -105,8 +105,8 @@ go install github.com/spf13/cobra-cli@latest For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) -For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md). +For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md). # License -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) +Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go index 2d0239437a..5f965e057f 100644 --- a/vendor/github.com/spf13/cobra/active_help.go +++ b/vendor/github.com/spf13/cobra/active_help.go @@ -17,6 +17,7 @@ package cobra import ( "fmt" "os" + "regexp" "strings" ) @@ -29,6 +30,8 @@ const ( activeHelpGlobalDisable = "0" ) +var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) + // AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. // Such strings will be processed by the completion script and will be shown as ActiveHelp // to the user. @@ -42,7 +45,7 @@ func AppendActiveHelp(compArray []string, activeHelpStr string) []string { // GetActiveHelpConfig returns the value of the ActiveHelp environment variable // _ACTIVE_HELP where is the name of the root command in upper -// case, with all - replaced by _. +// case, with all non-ASCII-alphanumeric characters replaced by `_`. // It will always return "0" if the global environment variable COBRA_ACTIVE_HELP // is set to "0". func GetActiveHelpConfig(cmd *Command) string { @@ -55,9 +58,10 @@ func GetActiveHelpConfig(cmd *Command) string { // activeHelpEnvVar returns the name of the program-specific ActiveHelp environment // variable. It has the format _ACTIVE_HELP where is the name of the -// root command in upper case, with all - replaced by _. +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. func activeHelpEnvVar(name string) string { // This format should not be changed: users will be using it explicitly. activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix)) - return strings.ReplaceAll(activeHelpEnvVar, "-", "_") + activeHelpEnvVar = activeHelpEnvVarPrefixSubstRegexp.ReplaceAllString(activeHelpEnvVar, "_") + return activeHelpEnvVar } diff --git a/vendor/github.com/spf13/cobra/active_help.md b/vendor/github.com/spf13/cobra/active_help.md deleted file mode 100644 index 5e7f59af38..0000000000 --- a/vendor/github.com/spf13/cobra/active_help.md +++ /dev/null @@ -1,157 +0,0 @@ -# Active Help - -Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion. - -For example, -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding. - -bash-5.1$ bin/helm package [tab] -Please specify the path to the chart to package - -bash-5.1$ bin/helm package [tab][tab] -bin/ internal/ scripts/ pkg/ testdata/ -``` - -**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program. -## Supported shells - -Active Help is currently only supported for the following shells: -- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed. -- Zsh - -## Adding Active Help messages - -As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md). - -Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details. - -### Active Help for nouns - -Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example: - -```go -cmd := &cobra.Command{ - Use: "add [NAME] [URL]", - Short: "add a chart repository", - Args: require.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - return addRepo(args) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - var comps []string - if len(args) == 0 { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } else if len(args) == 1 { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } else { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - return comps, cobra.ShellCompDirectiveNoFileComp - }, -} -``` -The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior: -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding - -bash-5.1$ helm repo add grafana [tab] -You must specify the URL for the repo you are adding - -bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab] -This command does not take any more arguments -``` -**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions. - -### Active Help for flags - -Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example: -```go -_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 2 { - return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp - } - return compVersionFlag(args[1], toComplete) - }) -``` -The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag. -``` -bash-5.1$ bin/helm install myrelease --version 2.0.[tab] -You must first specify the chart to install before the --version flag can be completed - -bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab] -2.0.1 2.0.2 2.0.3 -``` - -## User control of Active Help - -You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any. -Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration. - -The way to configure Active Help is to use the program's Active Help environment -variable. That variable is named `_ACTIVE_HELP` where `` is the name of your -program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever -Active Help configuration values are supported by the program. - -For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user -would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell. - -For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the -Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages -should or should not be added (instead of reading the environment variable directly). - -For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - activeHelpLevel := cobra.GetActiveHelpConfig(cmd) - - var comps []string - if len(args) == 0 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } - } else if len(args) == 1 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } - } else { - if activeHelpLevel == "local" { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - } - return comps, cobra.ShellCompDirectiveNoFileComp -}, -``` -**Note 1**: If the `_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly. - -**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `_ACTIVE_HELP` is set to. - -**Note 3**: If the user does not set `_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. -## Active Help with Cobra's default completion command - -Cobra provides a default `completion` command for programs that wish to use it. -When using the default `completion` command, Active Help is configurable in the same -fashion as described above using environment variables. You may wish to document this in more -details for your users. - -## Debugging Active Help - -Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details. - -When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below: -``` -$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -_activeHelp_ WARNING: cannot re-use a name that is still in use -:0 -Completion ended with directive: ShellCompDirectiveDefault - -$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -:0 -Completion ended with directive: ShellCompDirectiveDefault -``` diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 10c78847de..8a53151840 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -85,7 +85,7 @@ __%[1]s_handle_go_custom_completion() local out requestComp lastParam lastChar comp directive args # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + # Calling ${words[0]} instead of directly %[1]s allows handling aliases args=("${words[@]:1}") # Disable ActiveHelp which is not supported for bash completion v1 requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md deleted file mode 100644 index 52919b2fa6..0000000000 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ /dev/null @@ -1,93 +0,0 @@ -# Generating Bash Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. - -**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. - -The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. - -Some code that works in kubernetes: - -```bash -const ( - bash_completion_func = `__kubectl_parse_get() -{ - local kubectl_output out - if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then - out=($(echo "${kubectl_output}" | awk '{print $1}')) - COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get ${nouns[${#nouns[@]} -1]} - if [[ $? -eq 0 ]]; then - return 0 - fi -} - -__kubectl_custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) - __kubectl_get_resource - return - ;; - *) - ;; - esac -} -`) -``` - -And then I set that in my command definition: - -```go -cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, -} -``` - -The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! - -Similarly, for flags: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go index 19b09560c1..1cce5c329c 100644 --- a/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ b/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -57,7 +57,7 @@ __%[1]s_get_completion_results() { local requestComp lastParam lastChar args # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + # Calling ${words[0]} instead of directly %[1]s allows handling aliases args=("${words[@]:1}") requestComp="${words[0]} %[2]s ${args[*]}" diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index b07b44a0ce..a6b160ce53 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -43,12 +43,13 @@ var initializers []func() var finalizers []func() const ( - defaultPrefixMatching = false - defaultCommandSorting = true - defaultCaseInsensitive = false + defaultPrefixMatching = false + defaultCommandSorting = true + defaultCaseInsensitive = false + defaultTraverseRunHooks = false ) -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing +// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing // to automatically enable in CLI tools. // Set this to true to enable it. var EnablePrefixMatching = defaultPrefixMatching @@ -60,6 +61,10 @@ var EnableCommandSorting = defaultCommandSorting // EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) var EnableCaseInsensitive = defaultCaseInsensitive +// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. +// By default this is disabled, which means only the first run hook to be found is executed. +var EnableTraverseRunHooks = defaultTraverseRunHooks + // MousetrapHelpText enables an information splash screen on Windows // if the CLI is started from explorer.exe. // To disable the mousetrap, just set this variable to blank string (""). diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 01f7c6f1c5..2fbe6c131a 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -30,7 +30,10 @@ import ( flag "github.com/spf13/pflag" ) -const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" +const ( + FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" + CommandDisplayNameAnnotation = "cobra_annotation_command_display_name" +) // FParseErrWhitelist configures Flag parse errors to be ignored type FParseErrWhitelist flag.ParseErrorsWhitelist @@ -99,7 +102,7 @@ type Command struct { Deprecated string // Annotations are key/value pairs that can be used by applications to identify or - // group commands. + // group commands or set special options. Annotations map[string]string // Version defines the version for this command. If this value is non-empty and the command does not @@ -115,6 +118,8 @@ type Command struct { // * PostRun() // * PersistentPostRun() // All functions get the same args, the arguments after the command name. + // The *PreRun and *PostRun functions will only be executed if the Run function of the current + // command has been declared. // // PersistentPreRun: children of this command will inherit and execute. PersistentPreRun func(cmd *Command, args []string) @@ -181,6 +186,9 @@ type Command struct { // versionTemplate is the version template defined by user. versionTemplate string + // errPrefix is the error message prefix defined by user. + errPrefix string + // inReader is a reader defined by the user that replaces stdin inReader io.Reader // outWriter is a writer defined by the user that replaces stdout @@ -346,6 +354,11 @@ func (c *Command) SetVersionTemplate(s string) { c.versionTemplate = s } +// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. +func (c *Command) SetErrPrefix(s string) { + c.errPrefix = s +} + // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. // The user should not have a cyclic dependency on commands. func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { @@ -595,6 +608,18 @@ func (c *Command) VersionTemplate() string { ` } +// ErrPrefix return error message prefix for the command +func (c *Command) ErrPrefix() string { + if c.errPrefix != "" { + return c.errPrefix + } + + if c.HasParent() { + return c.parent.ErrPrefix() + } + return "Error:" +} + func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { flag := fs.Lookup(name) if flag == nil { @@ -752,7 +777,9 @@ func (c *Command) findNext(next string) *Command { } if len(matches) == 1 { - return matches[0] + // Temporarily disable gosec G602, which produces a false positive. + // See https://github.com/securego/gosec/issues/1005. + return matches[0] // #nosec G602 } return nil @@ -910,15 +937,31 @@ func (c *Command) execute(a []string) (err error) { return err } + parents := make([]*Command, 0, 5) for p := c; p != nil; p = p.Parent() { + if EnableTraverseRunHooks { + // When EnableTraverseRunHooks is set: + // - Execute all persistent pre-runs from the root parent till this command. + // - Execute all persistent post-runs from this command till the root parent. + parents = append([]*Command{p}, parents...) + } else { + // Otherwise, execute only the first found persistent hook. + parents = append(parents, p) + } + } + for _, p := range parents { if p.PersistentPreRunE != nil { if err := p.PersistentPreRunE(c, argWoFlags); err != nil { return err } - break + if !EnableTraverseRunHooks { + break + } } else if p.PersistentPreRun != nil { p.PersistentPreRun(c, argWoFlags) - break + if !EnableTraverseRunHooks { + break + } } } if c.PreRunE != nil { @@ -955,10 +998,14 @@ func (c *Command) execute(a []string) (err error) { if err := p.PersistentPostRunE(c, argWoFlags); err != nil { return err } - break + if !EnableTraverseRunHooks { + break + } } else if p.PersistentPostRun != nil { p.PersistentPostRun(c, argWoFlags) - break + if !EnableTraverseRunHooks { + break + } } } @@ -1048,7 +1095,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { c = cmd } if !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) + c.PrintErrln(c.ErrPrefix(), err.Error()) c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) } return c, err @@ -1077,7 +1124,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { // If root command has SilenceErrors flagged, // all subcommands should respect it if !cmd.SilenceErrors && !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) + c.PrintErrln(cmd.ErrPrefix(), err.Error()) } // If root command has SilenceUsage flagged, @@ -1380,6 +1427,9 @@ func (c *Command) CommandPath() string { if c.HasParent() { return c.Parent().CommandPath() + " " + c.Name() } + if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { + return displayName + } return c.Name() } @@ -1402,6 +1452,7 @@ func (c *Command) UseLine() string { // DebugFlags used to determine which flags have been assigned to which commands // and which persist. +// nolint:goconst func (c *Command) DebugFlags() { c.Println("DebugFlags called on", c.Name()) var debugflags func(*Command) diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go index ee38c4d0b8..b60f6b2000 100644 --- a/vendor/github.com/spf13/cobra/completions.go +++ b/vendor/github.com/spf13/cobra/completions.go @@ -145,6 +145,20 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman return nil } +// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. +func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) { + flag := c.Flag(flagName) + if flag == nil { + return nil, false + } + + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() + + completionFunc, exists := flagCompletionFunctions[flag] + return completionFunc, exists +} + // Returns a string listing the different directive enabled in the specified parameter func (d ShellCompDirective) string() string { var directives []string @@ -283,9 +297,13 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // These flags are normally added when `execute()` is called on `finalCmd`, // however, when doing completion, we don't call `finalCmd.execute()`. - // Let's add the --help and --version flag ourselves. - finalCmd.InitDefaultHelpFlag() - finalCmd.InitDefaultVersionFlag() + // Let's add the --help and --version flag ourselves but only if the finalCmd + // has not disabled flag parsing; if flag parsing is disabled, it is up to the + // finalCmd itself to handle the completion of *all* flags. + if !finalCmd.DisableFlagParsing { + finalCmd.InitDefaultHelpFlag() + finalCmd.InitDefaultVersionFlag() + } // Check if we are doing flag value completion before parsing the flags. // This is important because if we are completing a flag value, we need to also @@ -389,6 +407,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { doCompleteFlags(flag) }) + // Try to complete non-inherited flags even if DisableFlagParsing==true. + // This allows programs to tell Cobra about flags for completion even + // if the actual parsing of flags is not done by Cobra. + // For instance, Helm uses this to provide flag name completion for + // some of its plugins. finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { doCompleteFlags(flag) }) diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go index 12ca0d2b11..12d61b6911 100644 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -113,7 +113,7 @@ function __%[1]s_clear_perform_completion_once_result __%[1]s_debug "" __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" set --erase __%[1]s_perform_completion_once_result - __%[1]s_debug "Succesfully erased the variable __%[1]s_perform_completion_once_result" + __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result" end function __%[1]s_requires_order_preservation diff --git a/vendor/github.com/spf13/cobra/fish_completions.md b/vendor/github.com/spf13/cobra/fish_completions.md deleted file mode 100644 index 19b2ed1293..0000000000 --- a/vendor/github.com/spf13/cobra/fish_completions.md +++ /dev/null @@ -1,4 +0,0 @@ -## Generating Fish Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go index b35fde1554..0671ec5f20 100644 --- a/vendor/github.com/spf13/cobra/flag_groups.go +++ b/vendor/github.com/spf13/cobra/flag_groups.go @@ -24,6 +24,7 @@ import ( const ( requiredAsGroup = "cobra_annotation_required_if_others_set" + oneRequired = "cobra_annotation_one_required" mutuallyExclusive = "cobra_annotation_mutually_exclusive" ) @@ -43,6 +44,22 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { } } +// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors +// if the command is invoked without at least one flag from the given set of flags. +func (c *Command) MarkFlagsOneRequired(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) + } + if err := c.Flags().SetAnnotation(v, oneRequired, append(f.Annotations[oneRequired], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + // MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors // if the command is invoked with more than one flag from the given set of flags. func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { @@ -59,7 +76,7 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { } } -// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the +// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the // first error encountered. func (c *Command) ValidateFlagGroups() error { if c.DisableFlagParsing { @@ -71,15 +88,20 @@ func (c *Command) ValidateFlagGroups() error { // groupStatus format is the list of flags as a unique ID, // then a map of each flag name and whether it is set or not. groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} flags.VisitAll(func(pflag *flag.Flag) { processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus) processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) }) if err := validateRequiredFlagGroups(groupStatus); err != nil { return err } + if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil { + return err + } if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { return err } @@ -142,6 +164,27 @@ func validateRequiredFlagGroups(data map[string]map[string]bool) error { return nil } +func validateOneRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) >= 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList) + } + return nil +} + func validateExclusiveFlagGroups(data map[string]map[string]bool) error { keys := sortedKeys(data) for _, flagList := range keys { @@ -176,6 +219,7 @@ func sortedKeys(m map[string]map[string]bool) []string { // enforceFlagGroupsForCompletion will do the following: // - when a flag in a group is present, other flags in the group will be marked required +// - when none of the flags in a one-required group are present, all flags in the group will be marked required // - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden // This allows the standard completion logic to behave appropriately for flag groups func (c *Command) enforceFlagGroupsForCompletion() { @@ -185,9 +229,11 @@ func (c *Command) enforceFlagGroupsForCompletion() { flags := c.Flags() groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} c.Flags().VisitAll(func(pflag *flag.Flag) { processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus) processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) }) @@ -204,6 +250,26 @@ func (c *Command) enforceFlagGroupsForCompletion() { } } + // If none of the flags of a one-required group are present, we make all the flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range oneRequiredGroupStatus { + set := 0 + + for _, isSet := range flagnameAndStatus { + if isSet { + set++ + } + } + + // None of the flags of the group are set, mark all flags in the group + // as required + if set == 0 { + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + // If a flag that is mutually exclusive to others is present, we hide the other // flags of that group so the shell completion does not suggest them for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go index 177d2755f2..5519519394 100644 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -47,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars { `+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` } -[scriptblock]$__%[2]sCompleterBlock = { +[scriptblock]${__%[2]sCompleterBlock} = { param( $WordToComplete, $CommandAst, @@ -122,7 +122,7 @@ filter __%[1]s_escapeStringWithSpecialChars { __%[1]s_debug "Calling $RequestComp" # First disable ActiveHelp which is not supported for Powershell - $env:%[10]s=0 + ${env:%[10]s}=0 #call the command store the output in $out and redirect stderr and stdout to null # $Out is an array contains each line per element @@ -279,7 +279,7 @@ filter __%[1]s_escapeStringWithSpecialChars { } } -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock +Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} `, name, nameForVar, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) diff --git a/vendor/github.com/spf13/cobra/powershell_completions.md b/vendor/github.com/spf13/cobra/powershell_completions.md deleted file mode 100644 index c449f1e5c0..0000000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.md +++ /dev/null @@ -1,3 +0,0 @@ -# Generating PowerShell Completions For Your Own cobra.Command - -Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details. diff --git a/vendor/github.com/spf13/cobra/projects_using_cobra.md b/vendor/github.com/spf13/cobra/projects_using_cobra.md deleted file mode 100644 index 8a291eb20e..0000000000 --- a/vendor/github.com/spf13/cobra/projects_using_cobra.md +++ /dev/null @@ -1,64 +0,0 @@ -## Projects using Cobra - -- [Allero](https://github.com/allero-io/allero) -- [Arewefastyet](https://benchmark.vitess.io) -- [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](https://blevesearch.com/) -- [Cilium](https://cilium.io/) -- [CloudQuery](https://github.com/cloudquery/cloudquery) -- [CockroachDB](https://www.cockroachlabs.com/) -- [Constellation](https://github.com/edgelesssys/constellation) -- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) -- [Datree](https://github.com/datreeio/datree) -- [Delve](https://github.com/derekparker/delve) -- [Docker (distribution)](https://github.com/docker/distribution) -- [Etcd](https://etcd.io/) -- [Gardener](https://github.com/gardener/gardenctl) -- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) -- [Git Bump](https://github.com/erdaltsksn/git-bump) -- [GitHub CLI](https://github.com/cli/cli) -- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) -- [Golangci-lint](https://golangci-lint.run) -- [GopherJS](https://github.com/gopherjs/gopherjs) -- [GoReleaser](https://goreleaser.com) -- [Helm](https://helm.sh) -- [Hugo](https://gohugo.io) -- [Infracost](https://github.com/infracost/infracost) -- [Istio](https://istio.io) -- [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](https://kubernetes.io/) -- [Kubescape](https://github.com/kubescape/kubescape) -- [KubeVirt](https://github.com/kubevirt/kubevirt) -- [Linkerd](https://linkerd.io/) -- [Mattermost-server](https://github.com/mattermost/mattermost-server) -- [Mercure](https://mercure.rocks/) -- [Meroxa CLI](https://github.com/meroxa/cli) -- [Metal Stack CLI](https://github.com/metal-stack/metalctl) -- [Moby (former Docker)](https://github.com/moby/moby) -- [Moldy](https://github.com/Moldy-Community/moldy) -- [Multi-gitter](https://github.com/lindell/multi-gitter) -- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -- [nFPM](https://nfpm.goreleaser.com) -- [Okteto](https://github.com/okteto/okteto) -- [OpenShift](https://www.openshift.com/) -- [Ory Hydra](https://github.com/ory/hydra) -- [Ory Kratos](https://github.com/ory/kratos) -- [Pixie](https://github.com/pixie-io/pixie) -- [Polygon Edge](https://github.com/0xPolygon/polygon-edge) -- [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](https://www.projectatomic.io/) -- [Prototool](https://github.com/uber/prototool) -- [Pulumi](https://www.pulumi.com) -- [QRcp](https://github.com/claudiodangelis/qrcp) -- [Random](https://github.com/erdaltsksn/random) -- [Rclone](https://rclone.org/) -- [Scaleway CLI](https://github.com/scaleway/scaleway-cli) -- [Sia](https://github.com/SiaFoundation/siad) -- [Skaffold](https://skaffold.dev/) -- [Tendermint](https://github.com/tendermint/tendermint) -- [Twitch CLI](https://github.com/twitchdev/twitch-cli) -- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli) -- [Vitess](https://vitess.io) -- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework) -- [Werf](https://werf.io/) -- [ZITADEL](https://github.com/zitadel/zitadel) diff --git a/vendor/github.com/spf13/cobra/shell_completions.md b/vendor/github.com/spf13/cobra/shell_completions.md deleted file mode 100644 index 065c0621d4..0000000000 --- a/vendor/github.com/spf13/cobra/shell_completions.md +++ /dev/null @@ -1,576 +0,0 @@ -# Generating shell completions - -Cobra can generate shell completions for multiple shells. -The currently supported shells are: -- Bash -- Zsh -- fish -- PowerShell - -Cobra will automatically provide your program with a fully functional `completion` command, -similarly to how it provides the `help` command. - -## Creating your own completion command - -If you do not wish to use the default `completion` command, you can choose to -provide your own, which will take precedence over the default one. (This also provides -backwards-compatibility with programs that already have their own `completion` command.) - -If you are using the `cobra-cli` generator, -which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli), -you can create a completion command by running - -```bash -cobra-cli add completion -``` -and then modifying the generated `cmd/completion.go` file to look something like this -(writing the shell script to stdout allows the most flexible use): - -```go -var completionCmd = &cobra.Command{ - Use: "completion [bash|zsh|fish|powershell]", - Short: "Generate completion script", - Long: fmt.Sprintf(`To load completions: - -Bash: - - $ source <(%[1]s completion bash) - - # To load completions for each session, execute once: - # Linux: - $ %[1]s completion bash > /etc/bash_completion.d/%[1]s - # macOS: - $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s - -Zsh: - - # If shell completion is not already enabled in your environment, - # you will need to enable it. You can execute the following once: - - $ echo "autoload -U compinit; compinit" >> ~/.zshrc - - # To load completions for each session, execute once: - $ %[1]s completion zsh > "${fpath[1]}/_%[1]s" - - # You will need to start a new shell for this setup to take effect. - -fish: - - $ %[1]s completion fish | source - - # To load completions for each session, execute once: - $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -PowerShell: - - PS> %[1]s completion powershell | Out-String | Invoke-Expression - - # To load completions for every new session, run: - PS> %[1]s completion powershell > %[1]s.ps1 - # and source this file from your PowerShell profile. -`,cmd.Root().Name()), - DisableFlagsInUseLine: true, - ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - switch args[0] { - case "bash": - cmd.Root().GenBashCompletion(os.Stdout) - case "zsh": - cmd.Root().GenZshCompletion(os.Stdout) - case "fish": - cmd.Root().GenFishCompletion(os.Stdout, true) - case "powershell": - cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) - } - }, -} -``` - -**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. - -## Adapting the default completion command - -Cobra provides a few options for the default `completion` command. To configure such options you must set -the `CompletionOptions` field on the *root* command. - -To tell Cobra *not* to provide the default `completion` command: -``` -rootCmd.CompletionOptions.DisableDefaultCmd = true -``` - -To tell Cobra to mark the default `completion` command as *hidden*: -``` -rootCmd.CompletionOptions.HiddenDefaultCmd = true -``` - -To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: -``` -rootCmd.CompletionOptions.DisableNoDescFlag = true -``` - -To tell Cobra to completely disable descriptions for completions: -``` -rootCmd.CompletionOptions.DisableDescriptions = true -``` - -# Customizing completions - -The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. - -## Completion of nouns - -### Static completion of nouns - -Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field. -For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. -Some simplified code from `kubectl get` looks like: - -```go -validArgs = []string{ "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - cobra.CheckErr(RunGet(f, out, cmd, args)) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like: - -```bash -$ kubectl get [tab][tab] -node pod replicationcontroller service -``` - -#### Aliases for nouns - -If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`. - -### Dynamic completion of nouns - -In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. -Simplified code from `helm status` looks like: - -```go -cmd := &cobra.Command{ - Use: "status RELEASE_NAME", - Short: "Display the status of the named release", - Long: status_long, - RunE: func(cmd *cobra.Command, args []string) { - RunGet(args[0]) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 0 { - return nil, cobra.ShellCompDirectiveNoFileComp - } - return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp - }, -} -``` -Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. -Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like: - -```bash -$ helm status [tab][tab] -harbor notary rook thanos -``` -You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` -```go -// Indicates that the shell will perform its default behavior after completions -// have been provided (this implies none of the other directives). -ShellCompDirectiveDefault - -// Indicates an error occurred and completions should be ignored. -ShellCompDirectiveError - -// Indicates that the shell should not add a space after the completion, -// even if there is a single completion provided. -ShellCompDirectiveNoSpace - -// Indicates that the shell should not provide file completion even when -// no completion is provided. -ShellCompDirectiveNoFileComp - -// Indicates that the returned completions should be used as file extension filters. -// For example, to complete only files of the form *.json or *.yaml: -// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt -// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() -// is a shortcut to using this directive explicitly. -// -ShellCompDirectiveFilterFileExt - -// Indicates that only directory names should be provided in file completion. -// For example: -// return nil, ShellCompDirectiveFilterDirs -// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. -// -// To request directory names within another directory, the returned completions -// should specify a single directory name within which to search. For example, -// to complete directories within "themes/": -// return []string{"themes"}, ShellCompDirectiveFilterDirs -// -ShellCompDirectiveFilterDirs - -// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order -// in which the completions are provided -ShellCompDirectiveKeepOrder -``` - -***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. - -#### Debugging - -Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: -```bash -$ helm __complete status har -harbor -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command: -```bash -$ helm __complete status "" -harbor -notary -rook -thanos -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: -```go -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and optionally prints to stderr. -cobra.CompDebug(msg string, printToStdErr bool) { -cobra.CompDebugln(msg string, printToStdErr bool) - -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and to stderr. -cobra.CompError(msg string) -cobra.CompErrorln(msg string) -``` -***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. - -## Completions for flags - -### Mark flags as required - -Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so: - -```go -cmd.MarkFlagRequired("pod") -cmd.MarkFlagRequired("container") -``` - -and you'll get something like - -```bash -$ kubectl exec [tab][tab] --c --container= -p --pod= -``` - -### Specify dynamic flag completion - -As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function. - -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault -}) -``` -Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: - -```bash -$ helm status --output [tab][tab] -json table yaml -``` - -#### Debugging - -You can also easily debug your Go completion code for flags: -```bash -$ helm __complete status --output "" -json -table -yaml -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above. - -### Specify valid filename extensions for flags that take a filename - -To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so: -```go -flagName := "output" -cmd.MarkFlagFilename(flagName, "yaml", "json") -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt}) -``` - -### Limit flag completions to directory names - -To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so: -```go -flagName := "output" -cmd.MarkFlagDirname(flagName) -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs -}) -``` -To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs -}) -``` -### Descriptions for completions - -Cobra provides support for completion descriptions. Such descriptions are supported for each shell -(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). -For commands and flags, Cobra will provide the descriptions automatically, based on usage information. -For example, using zsh: -``` -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release -``` -while using fish: -``` -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) -``` - -Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp -}} -``` -or -```go -ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} -``` - -If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like: - -```bash -$ source <(helm completion bash) -$ helm completion [tab][tab] -bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell) -fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh) - -$ source <(helm completion bash --no-descriptions) -$ helm completion [tab][tab] -bash fish powershell zsh -``` -## Bash completions - -### Dependencies - -The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)) - -### Aliases - -You can also configure `bash` aliases for your program and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -### Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. -Please refer to [Bash Completions](bash_completions.md) for details. - -### Bash completion V2 - -Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling -`GenBashCompletion()` or `GenBashCompletionFile()`. - -A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or -`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion -(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion -solution described in this document. -Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash -completion V2 solution which provides the following extra features: -- Supports completion descriptions (like the other shells) -- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) -- Streamlined user experience thanks to a completion behavior aligned with the other shells - -`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` -you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra -will provide the description automatically based on usage information. You can choose to make this option configurable by -your users. - -``` -# With descriptions -$ helm s[tab][tab] -search (search for a keyword in charts) status (display the status of the named release) -show (show information of a chart) - -# Without descriptions -$ helm s[tab][tab] -search show status -``` -**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. -## Zsh completions - -Cobra supports native zsh completion generated from the root `cobra.Command`. -The generated completion script should be put somewhere in your `$fpath` and be named -`_`. You will need to start a new shell for the completions to become available. - -Zsh supports descriptions for completions. Cobra will provide the description automatically, -based on usage information. Cobra provides a way to completely disable such descriptions by -using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make -this a configurable option to your users. -``` -# With descriptions -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`. - * You should instead use `RegisterFlagCompletionFunc()`. - -### Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced. -Please refer to [Zsh Completions](zsh_completions.md) for details. - -## fish completions - -Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. -``` -# With descriptions -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `fish`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `fish`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) - -## PowerShell completions - -Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. - -The script is designed to support all three PowerShell completion modes: - -* TabCompleteNext (default windows style - on each key press the next option is displayed) -* Complete (works like bash) -* MenuComplete (works like zsh) - -You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function `. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode. - -Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles. - -``` -# With descriptions and Mode 'Complete' -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions. -$ helm s[tab] -search show status - -search for a keyword in charts - -# Without descriptions -$ helm s[tab] -search show status -``` -### Aliases - -You can also configure `powershell` aliases for your program and they will also support completions. - -``` -$ sal aliasname origcommand -$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -The name of the completer block variable is of the form `$__CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `powershell`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `powershell`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) diff --git a/vendor/github.com/spf13/cobra/user_guide.md b/vendor/github.com/spf13/cobra/user_guide.md deleted file mode 100644 index 85201d840c..0000000000 --- a/vendor/github.com/spf13/cobra/user_guide.md +++ /dev/null @@ -1,726 +0,0 @@ -# User Guide - -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra-CLI is its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at https://gohugo.io/documentation/`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra-cli", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Organizing subcommands - -A command may have subcommands which in turn may have other subcommands. This is achieved by using -`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in -its own go package. - -The suggested approach is for the parent command to use `AddCommand` to add its most immediate -subcommands. For example, consider the following directory structure: - -```text -├── cmd -│   ├── root.go -│   └── sub1 -│   ├── sub1.go -│   └── sub2 -│   ├── leafA.go -│   ├── leafB.go -│   └── sub2.go -└── main.go -``` - -In this case: - -* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command. -* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command. -* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the - sub2 command. - -This approach ensures the subcommands are always included at compile time while avoiding cyclic -references. - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -### Flag Groups - -If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then -Cobra can enforce that requirement: -```go -rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") -rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") -rootCmd.MarkFlagsRequiredTogether("username", "password") -``` - -You can also prevent different flags from being provided together if they represent mutually -exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: -```go -rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") -rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") -rootCmd.MarkFlagsMutuallyExclusive("json", "yaml") -``` - -In both of these cases: - - both local and persistent flags can be used - - **NOTE:** the group is only enforced on commands where every flag is defined - - a flag may appear in multiple groups - - a group may contain any number of flags - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field of `Command`. -The following validators are built in: - -- Number of arguments: - - `NoArgs` - report an error if there are any positional args. - - `ArbitraryArgs` - accept any number of args. - - `MinimumNArgs(int)` - report an error if less than N positional args are provided. - - `MaximumNArgs(int)` - report an error if more than N positional args are provided. - - `ExactArgs(int)` - report an error if there are not exactly N positional args. - - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`. -- Content of the arguments: - - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args. - -If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. - -Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks. -For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional -args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as -shown below: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`. -For example: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - // Optionally run one of the validators provided by cobra - if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { - return err - } - // Run the custom validation logic - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra-cli help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra-cli [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Grouping commands in help - -Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly -defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element -of that subcommand. The groups will appear in the help output in the same order as they are defined using different -calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using -`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with the following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra-cli --invalid - Error: unknown flag: --invalid - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which -you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). - -## Providing Active Help - -Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md). diff --git a/vendor/github.com/spf13/cobra/zsh_completions.md b/vendor/github.com/spf13/cobra/zsh_completions.md deleted file mode 100644 index 7cff61787f..0000000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.md +++ /dev/null @@ -1,48 +0,0 @@ -## Generating Zsh Completion For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced. - -### Deprecation summary - -See further below for more details on these deprecations. - -* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored. -* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`. -* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction`. - -### Behavioral changes - -**Noun completion** -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis| -|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`| -`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored| -|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)| -|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior| - -**Flag-value completion** - -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion| -|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored| -|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)| -|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells| -|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`| -|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`| - -**Improvements** - -* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`) -* File completion by default if no other completions found -* Handling of required flags -* File extension filtering no longer mutually exclusive with bash usage -* Completion of directory names *within* another directory -* Support for `=` form of flags diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go index 303e5505e4..9509014e87 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go @@ -34,7 +34,7 @@ const ( RequestCount = "http.server.request_count" // Incoming request count total RequestContentLength = "http.server.request_content_length" // Incoming request bytes total ResponseContentLength = "http.server.response_content_length" // Incoming response bytes total - ServerLatency = "http.server.duration" // Incoming end to end duration, microseconds + ServerLatency = "http.server.duration" // Incoming end to end duration, milliseconds ) // Filter is a predicate used to determine whether a given http.request should @@ -42,5 +42,5 @@ const ( type Filter func(*http.Request) bool func newTracer(tp trace.TracerProvider) trace.Tracer { - return tp.Tracer(instrumentationName, trace.WithInstrumentationVersion(Version())) + return tp.Tracer(ScopeName, trace.WithInstrumentationVersion(Version())) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go index e4fa1b8d9d..a1b5b5e5aa 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go @@ -25,9 +25,8 @@ import ( "go.opentelemetry.io/otel/trace" ) -const ( - instrumentationName = "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" -) +// ScopeName is the instrumentation scope name. +const ScopeName = "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" // config represents the configuration options available for the http.Handler // and http.Transport types. @@ -76,7 +75,7 @@ func newConfig(opts ...Option) *config { } c.Meter = c.MeterProvider.Meter( - instrumentationName, + ScopeName, metric.WithInstrumentationVersion(Version()), ) diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index b2fbe07841..9a8260059d 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -107,13 +107,25 @@ func (h *middleware) createMeasures() { h.counters = make(map[string]metric.Int64Counter) h.valueRecorders = make(map[string]metric.Float64Histogram) - requestBytesCounter, err := h.meter.Int64Counter(RequestContentLength) + requestBytesCounter, err := h.meter.Int64Counter( + RequestContentLength, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP request content length (uncompressed)"), + ) handleErr(err) - responseBytesCounter, err := h.meter.Int64Counter(ResponseContentLength) + responseBytesCounter, err := h.meter.Int64Counter( + ResponseContentLength, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP response content length (uncompressed)"), + ) handleErr(err) - serverLatencyMeasure, err := h.meter.Float64Histogram(ServerLatency) + serverLatencyMeasure, err := h.meter.Float64Histogram( + ServerLatency, + metric.WithUnit("ms"), + metric.WithDescription("Measures the duration of HTTP request handling"), + ) handleErr(err) h.counters[RequestContentLength] = requestBytesCounter diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index 6eace875cf..8a5cf07bd2 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -16,7 +16,7 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http // Version is the current release version of the otelhttp instrumentation. func Version() string { - return "0.45.0" + return "0.46.0" // This string is updated by the pre_release.sh script during release } diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go index 5dfacbb983..661ea132e0 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego package chacha20 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s index f1f66230d1..7dd2638e88 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s +++ b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go index 02ff3d05e9..db42e6676a 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build (!arm64 && !s390x && !ppc64le) || !gc || purego -// +build !arm64,!s390x,!ppc64le !gc purego package chacha20 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go index da420b2e97..3a4287f990 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego package chacha20 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s index 5c0fed26f8..66aebae258 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s +++ b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s @@ -20,7 +20,6 @@ // due to the calling conventions and initialization of constants. //go:build gc && !purego -// +build gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go index 4652247b8a..683ccfd1c3 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego package chacha20 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_s390x.s b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.s index f3ef5a019d..1eda91a3d4 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_s390x.s +++ b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego #include "go_asm.h" #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go index edcf163c4e..70c541692c 100644 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go +++ b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go @@ -1,7 +1,6 @@ // Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. //go:build amd64 && gc && !purego -// +build amd64,gc,!purego package field diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s index 293f013c94..60817acc41 100644 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s @@ -1,7 +1,6 @@ // Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. //go:build amd64 && gc && !purego -// +build amd64,gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go index ddb6c9b8f7..9da280d1d8 100644 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go +++ b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !amd64 || !gc || purego -// +build !amd64 !gc purego package field diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go index af459ef515..075fe9b925 100644 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go +++ b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && gc && !purego -// +build arm64,gc,!purego package field diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s index 5c91e45892..3126a43419 100644 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s +++ b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && gc && !purego -// +build arm64,gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go index 234a5b2e5d..fc029ac12d 100644 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go +++ b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !arm64 || !gc || purego -// +build !arm64 !gc purego package field diff --git a/vendor/golang.org/x/crypto/hkdf/hkdf.go b/vendor/golang.org/x/crypto/hkdf/hkdf.go index dda3f143be..f4ded5fee2 100644 --- a/vendor/golang.org/x/crypto/hkdf/hkdf.go +++ b/vendor/golang.org/x/crypto/hkdf/hkdf.go @@ -56,7 +56,9 @@ func (f *hkdf) Read(p []byte) (int, error) { // Fill the rest of the buffer for len(p) > 0 { - f.expander.Reset() + if f.counter > 1 { + f.expander.Reset() + } f.expander.Write(f.prev) f.expander.Write(f.info) f.expander.Write([]byte{f.counter}) diff --git a/vendor/golang.org/x/crypto/internal/alias/alias.go b/vendor/golang.org/x/crypto/internal/alias/alias.go index 69c17f822b..551ff0c353 100644 --- a/vendor/golang.org/x/crypto/internal/alias/alias.go +++ b/vendor/golang.org/x/crypto/internal/alias/alias.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !purego -// +build !purego // Package alias implements memory aliasing tests. package alias diff --git a/vendor/golang.org/x/crypto/internal/alias/alias_purego.go b/vendor/golang.org/x/crypto/internal/alias/alias_purego.go index 4775b0a438..6fe61b5c6e 100644 --- a/vendor/golang.org/x/crypto/internal/alias/alias_purego.go +++ b/vendor/golang.org/x/crypto/internal/alias/alias_purego.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build purego -// +build purego // Package alias implements memory aliasing tests. package alias diff --git a/vendor/golang.org/x/crypto/internal/poly1305/bits_compat.go b/vendor/golang.org/x/crypto/internal/poly1305/bits_compat.go index 45b5c966b2..d33c8890fc 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/bits_compat.go +++ b/vendor/golang.org/x/crypto/internal/poly1305/bits_compat.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !go1.13 -// +build !go1.13 package poly1305 diff --git a/vendor/golang.org/x/crypto/internal/poly1305/bits_go1.13.go b/vendor/golang.org/x/crypto/internal/poly1305/bits_go1.13.go index ed52b3418a..495c1fa697 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/bits_go1.13.go +++ b/vendor/golang.org/x/crypto/internal/poly1305/bits_go1.13.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build go1.13 -// +build go1.13 package poly1305 diff --git a/vendor/golang.org/x/crypto/internal/poly1305/mac_noasm.go b/vendor/golang.org/x/crypto/internal/poly1305/mac_noasm.go index f184b67d98..333da285b3 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/mac_noasm.go +++ b/vendor/golang.org/x/crypto/internal/poly1305/mac_noasm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build (!amd64 && !ppc64le && !s390x) || !gc || purego -// +build !amd64,!ppc64le,!s390x !gc purego package poly1305 diff --git a/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.go b/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.go index 6d522333f2..164cd47d32 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.go +++ b/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego package poly1305 diff --git a/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.s b/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.s index 1d74f0f881..e0d3c64756 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.s +++ b/vendor/golang.org/x/crypto/internal/poly1305/sum_amd64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.go b/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.go index 4a069941a6..4aec4874b5 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.go +++ b/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego package poly1305 diff --git a/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.s b/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.s index 58422aad23..d2ca5deeb9 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.s +++ b/vendor/golang.org/x/crypto/internal/poly1305/sum_ppc64le.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.go b/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.go index ec95966889..e1d033a491 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.go +++ b/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego package poly1305 diff --git a/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.s b/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.s index aa9e0494c9..0fe3a7c217 100644 --- a/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.s +++ b/vendor/golang.org/x/crypto/internal/poly1305/sum_s390x.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc && !purego -// +build gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go index c400dfcf7b..e76b44fe59 100644 --- a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && !purego && gc -// +build amd64,!purego,gc package salsa diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s index c089277204..fcce0234b6 100644 --- a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && !purego && gc -// +build amd64,!purego,gc // This code was translated into a form compatible with 6a from the public // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go index 4392cc1ac7..9448760f26 100644 --- a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go +++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_noasm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !amd64 || purego || !gc -// +build !amd64 purego !gc package salsa diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go index b419c761ed..dd2ab0d69a 100644 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ b/vendor/golang.org/x/crypto/ssh/common.go @@ -10,7 +10,6 @@ import ( "fmt" "io" "math" - "strings" "sync" _ "crypto/sha1" @@ -140,8 +139,6 @@ var supportedPubKeyAuthAlgos = []string{ KeyAlgoDSA, } -var supportedPubKeyAuthAlgosList = strings.Join(supportedPubKeyAuthAlgos, ",") - // unexpectedMessageError results when the SSH message that we received didn't // match what we wanted. func unexpectedMessageError(expected, got uint8) error { diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go index 70a7369ff9..49bbba7692 100644 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ b/vendor/golang.org/x/crypto/ssh/handshake.go @@ -11,6 +11,7 @@ import ( "io" "log" "net" + "strings" "sync" ) @@ -50,6 +51,10 @@ type handshakeTransport struct { // connection. hostKeys []Signer + // publicKeyAuthAlgorithms is non-empty if we are the server. In that case, + // it contains the supported client public key authentication algorithms. + publicKeyAuthAlgorithms []string + // hostKeyAlgorithms is non-empty if we are the client. In that case, // we accept these key types from the server as host key. hostKeyAlgorithms []string @@ -141,6 +146,7 @@ func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byt func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport { t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) t.hostKeys = config.hostKeys + t.publicKeyAuthAlgorithms = config.PublicKeyAuthAlgorithms go t.readLoop() go t.kexLoop() return t @@ -649,6 +655,7 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { // message with the server-sig-algs extension if the client supports it. See // RFC 8308, Sections 2.4 and 3.1, and [PROTOCOL], Section 1.9. if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") { + supportedPubKeyAuthAlgosList := strings.Join(t.publicKeyAuthAlgorithms, ",") extInfo := &extInfoMsg{ NumExtensions: 2, Payload: make([]byte, 0, 4+15+4+len(supportedPubKeyAuthAlgosList)+4+16+4+1), diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index ef1bad731b..df4ebdada5 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -1232,16 +1232,27 @@ func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err) } + var result interface{} + switch block.Type { case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(buf) + result, err = x509.ParsePKCS1PrivateKey(buf) case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(buf) + result, err = x509.ParseECPrivateKey(buf) case "DSA PRIVATE KEY": - return ParseDSAPrivateKey(buf) + result, err = ParseDSAPrivateKey(buf) default: - return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) + err = fmt.Errorf("ssh: unsupported key type %q", block.Type) } + // Because of deficiencies in the format, DecryptPEMBlock does not always + // detect an incorrect password. In these cases decrypted DER bytes is + // random noise. If the parsing of the key returns an asn1.StructuralError + // we return x509.IncorrectPasswordError. + if _, ok := err.(asn1.StructuralError); ok { + return nil, x509.IncorrectPasswordError + } + + return result, err } // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go index 727c71b9c7..8f1505af94 100644 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ b/vendor/golang.org/x/crypto/ssh/server.go @@ -64,6 +64,13 @@ type ServerConfig struct { // Config contains configuration shared between client and server. Config + // PublicKeyAuthAlgorithms specifies the supported client public key + // authentication algorithms. Note that this should not include certificate + // types since those use the underlying algorithm. This list is sent to the + // client if it supports the server-sig-algs extension. Order is irrelevant. + // If unspecified then a default set of algorithms is used. + PublicKeyAuthAlgorithms []string + hostKeys []Signer // NoClientAuth is true if clients are allowed to connect without @@ -201,6 +208,15 @@ func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewCha if fullConf.MaxAuthTries == 0 { fullConf.MaxAuthTries = 6 } + if len(fullConf.PublicKeyAuthAlgorithms) == 0 { + fullConf.PublicKeyAuthAlgorithms = supportedPubKeyAuthAlgos + } else { + for _, algo := range fullConf.PublicKeyAuthAlgorithms { + if !contains(supportedPubKeyAuthAlgos, algo) { + return nil, nil, nil, fmt.Errorf("ssh: unsupported public key authentication algorithm %s", algo) + } + } + } // Check if the config contains any unsupported key exchanges for _, kex := range fullConf.KeyExchanges { if _, ok := serverForbiddenKexAlgos[kex]; ok { @@ -524,7 +540,7 @@ userAuthLoop: return nil, parseError(msgUserAuthRequest) } algo := string(algoBytes) - if !contains(supportedPubKeyAuthAlgos, underlyingAlgo(algo)) { + if !contains(config.PublicKeyAuthAlgorithms, underlyingAlgo(algo)) { authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo) break } @@ -591,7 +607,7 @@ userAuthLoop: // algorithm name that corresponds to algo with // sig.Format. This is usually the same, but // for certs, the names differ. - if !contains(supportedPubKeyAuthAlgos, sig.Format) { + if !contains(config.PublicKeyAuthAlgorithms, sig.Format) { authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format) break } diff --git a/vendor/golang.org/x/sync/errgroup/go120.go b/vendor/golang.org/x/sync/errgroup/go120.go index 7d419d3760..f93c740b63 100644 --- a/vendor/golang.org/x/sync/errgroup/go120.go +++ b/vendor/golang.org/x/sync/errgroup/go120.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build go1.20 -// +build go1.20 package errgroup diff --git a/vendor/golang.org/x/sync/errgroup/pre_go120.go b/vendor/golang.org/x/sync/errgroup/pre_go120.go index 1795c18ace..88ce33434e 100644 --- a/vendor/golang.org/x/sync/errgroup/pre_go120.go +++ b/vendor/golang.org/x/sync/errgroup/pre_go120.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !go1.20 -// +build !go1.20 package errgroup diff --git a/vendor/golang.org/x/term/term_unix.go b/vendor/golang.org/x/term/term_unix.go index 62c2b3f41f..1ad0ddfe30 100644 --- a/vendor/golang.org/x/term/term_unix.go +++ b/vendor/golang.org/x/term/term_unix.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package term diff --git a/vendor/golang.org/x/term/term_unix_bsd.go b/vendor/golang.org/x/term/term_unix_bsd.go index 853b3d6986..9dbf546298 100644 --- a/vendor/golang.org/x/term/term_unix_bsd.go +++ b/vendor/golang.org/x/term/term_unix_bsd.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build darwin || dragonfly || freebsd || netbsd || openbsd -// +build darwin dragonfly freebsd netbsd openbsd package term diff --git a/vendor/golang.org/x/term/term_unix_other.go b/vendor/golang.org/x/term/term_unix_other.go index 1e8955c934..1b36de799a 100644 --- a/vendor/golang.org/x/term/term_unix_other.go +++ b/vendor/golang.org/x/term/term_unix_other.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || linux || solaris || zos -// +build aix linux solaris zos package term diff --git a/vendor/golang.org/x/term/term_unsupported.go b/vendor/golang.org/x/term/term_unsupported.go index f1df850651..3c409e5885 100644 --- a/vendor/golang.org/x/term/term_unsupported.go +++ b/vendor/golang.org/x/term/term_unsupported.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !zos && !windows && !solaris && !plan9 -// +build !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!zos,!windows,!solaris,!plan9 package term diff --git a/vendor/golang.org/x/text/message/catalog/go19.go b/vendor/golang.org/x/text/message/catalog/go19.go index 4e5e87f8fa..291a4df949 100644 --- a/vendor/golang.org/x/text/message/catalog/go19.go +++ b/vendor/golang.org/x/text/message/catalog/go19.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build go1.9 -// +build go1.9 package catalog diff --git a/vendor/golang.org/x/text/message/catalog/gopre19.go b/vendor/golang.org/x/text/message/catalog/gopre19.go index 9e14685a58..da44ebb8be 100644 --- a/vendor/golang.org/x/text/message/catalog/gopre19.go +++ b/vendor/golang.org/x/text/message/catalog/gopre19.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !go1.9 -// +build !go1.9 package catalog diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go b/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go index 8a7392c4a1..784bb88087 100644 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build go1.10 -// +build go1.10 package bidirule diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go b/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go index bb0a920018..8e1e943955 100644 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !go1.10 -// +build !go1.10 package bidirule diff --git a/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go index 42fa8d72ce..d2bd71181d 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.10 && !go1.13 -// +build go1.10,!go1.13 package bidi diff --git a/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go index 56a0e1ea21..f76bdca273 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.13 && !go1.14 -// +build go1.13,!go1.14 package bidi diff --git a/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go index baacf32b43..3aa2c3bdf8 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.14 && !go1.16 -// +build go1.14,!go1.16 package bidi diff --git a/vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go index ffadb7bebd..a713757906 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.16 && !go1.21 -// +build go1.16,!go1.21 package bidi diff --git a/vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go index 92cce5802c..f15746f7df 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.21 -// +build go1.21 package bidi diff --git a/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go index f517fdb202..c164d37917 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build !go1.10 -// +build !go1.10 package bidi diff --git a/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go index f5a0788277..1af161c756 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.10 && !go1.13 -// +build go1.10,!go1.13 package norm diff --git a/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go index cb7239c437..eb73ecc373 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.13 && !go1.14 -// +build go1.13,!go1.14 package norm diff --git a/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go index 11b2733001..276cb8d8c0 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.14 && !go1.16 -// +build go1.14,!go1.16 package norm diff --git a/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go index f65785e8ac..0cceffd731 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.16 && !go1.21 -// +build go1.16,!go1.21 package norm diff --git a/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go index e1858b879d..b0819e42d0 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.21 -// +build go1.21 package norm diff --git a/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go index 0175eae50a..bf65457d9b 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build !go1.10 -// +build !go1.10 package norm diff --git a/vendor/golang.org/x/text/width/tables10.0.0.go b/vendor/golang.org/x/text/width/tables10.0.0.go index cd9d91cafb..07c1cb17af 100644 --- a/vendor/golang.org/x/text/width/tables10.0.0.go +++ b/vendor/golang.org/x/text/width/tables10.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.10 && !go1.13 -// +build go1.10,!go1.13 package width diff --git a/vendor/golang.org/x/text/width/tables11.0.0.go b/vendor/golang.org/x/text/width/tables11.0.0.go index 327eaef9b7..89288b3dae 100644 --- a/vendor/golang.org/x/text/width/tables11.0.0.go +++ b/vendor/golang.org/x/text/width/tables11.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.13 && !go1.14 -// +build go1.13,!go1.14 package width diff --git a/vendor/golang.org/x/text/width/tables12.0.0.go b/vendor/golang.org/x/text/width/tables12.0.0.go index 5c14ade6d9..755ee91221 100644 --- a/vendor/golang.org/x/text/width/tables12.0.0.go +++ b/vendor/golang.org/x/text/width/tables12.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.14 && !go1.16 -// +build go1.14,!go1.16 package width diff --git a/vendor/golang.org/x/text/width/tables13.0.0.go b/vendor/golang.org/x/text/width/tables13.0.0.go index b1fcb522cb..40c169edf6 100644 --- a/vendor/golang.org/x/text/width/tables13.0.0.go +++ b/vendor/golang.org/x/text/width/tables13.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.16 && !go1.21 -// +build go1.16,!go1.21 package width diff --git a/vendor/golang.org/x/text/width/tables15.0.0.go b/vendor/golang.org/x/text/width/tables15.0.0.go index 4b91e3384d..2b85289675 100644 --- a/vendor/golang.org/x/text/width/tables15.0.0.go +++ b/vendor/golang.org/x/text/width/tables15.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.21 -// +build go1.21 package width diff --git a/vendor/golang.org/x/text/width/tables9.0.0.go b/vendor/golang.org/x/text/width/tables9.0.0.go index 6781f3d960..d981330a9f 100644 --- a/vendor/golang.org/x/text/width/tables9.0.0.go +++ b/vendor/golang.org/x/text/width/tables9.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build !go1.10 -// +build !go1.10 package width diff --git a/vendor/golang.org/x/tools/cmd/stringer/stringer.go b/vendor/golang.org/x/tools/cmd/stringer/stringer.go index 998d1a51bf..2b19c93e8e 100644 --- a/vendor/golang.org/x/tools/cmd/stringer/stringer.go +++ b/vendor/golang.org/x/tools/cmd/stringer/stringer.go @@ -188,6 +188,8 @@ type Generator struct { trimPrefix string lineComment bool + + logf func(format string, args ...interface{}) // test logging hook; nil when not testing } func (g *Generator) Printf(format string, args ...interface{}) { @@ -221,13 +223,14 @@ func (g *Generator) parsePackage(patterns []string, tags []string) { // in a separate pass? For later. Tests: false, BuildFlags: []string{fmt.Sprintf("-tags=%s", strings.Join(tags, " "))}, + Logf: g.logf, } pkgs, err := packages.Load(cfg, patterns...) if err != nil { log.Fatal(err) } if len(pkgs) != 1 { - log.Fatalf("error: %d packages found", len(pkgs)) + log.Fatalf("error: %d packages matching %v", len(pkgs), strings.Join(patterns, " ")) } g.addPackage(pkgs[0]) } diff --git a/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go b/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go index 18a002f82a..0454cdd78e 100644 --- a/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go +++ b/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go @@ -8,7 +8,6 @@ package packagesdriver import ( "context" "fmt" - "go/types" "strings" "golang.org/x/tools/internal/gocommand" @@ -16,7 +15,7 @@ import ( var debug = false -func GetSizesGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (types.Sizes, error) { +func GetSizesForArgsGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (string, string, error) { inv.Verb = "list" inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"} stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv) @@ -29,21 +28,21 @@ func GetSizesGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner * inv.Args = []string{"GOARCH"} envout, enverr := gocmdRunner.Run(ctx, inv) if enverr != nil { - return nil, enverr + return "", "", enverr } goarch = strings.TrimSpace(envout.String()) compiler = "gc" } else { - return nil, friendlyErr + return "", "", friendlyErr } } else { fields := strings.Fields(stdout.String()) if len(fields) < 2 { - return nil, fmt.Errorf("could not parse GOARCH and Go compiler in format \" \":\nstdout: <<%s>>\nstderr: <<%s>>", + return "", "", fmt.Errorf("could not parse GOARCH and Go compiler in format \" \":\nstdout: <<%s>>\nstderr: <<%s>>", stdout.String(), stderr.String()) } goarch = fields[0] compiler = fields[1] } - return types.SizesFor(compiler, goarch), nil + return compiler, goarch, nil } diff --git a/vendor/golang.org/x/tools/go/packages/doc.go b/vendor/golang.org/x/tools/go/packages/doc.go index da4ab89fe6..a7a8f73e3d 100644 --- a/vendor/golang.org/x/tools/go/packages/doc.go +++ b/vendor/golang.org/x/tools/go/packages/doc.go @@ -35,7 +35,7 @@ The Package struct provides basic information about the package, including - Imports, a map from source import strings to the Packages they name; - Types, the type information for the package's exported symbols; - Syntax, the parsed syntax trees for the package's source code; and - - TypeInfo, the result of a complete type-check of the package syntax trees. + - TypesInfo, the result of a complete type-check of the package syntax trees. (See the documentation for type Package for the complete list of fields and more detailed descriptions.) diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 58230038a7..1f1eade0ac 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -9,8 +9,6 @@ import ( "context" "encoding/json" "fmt" - "go/types" - "io/ioutil" "log" "os" "path" @@ -153,10 +151,10 @@ func goListDriver(cfg *Config, patterns ...string) (*driverResponse, error) { if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&NeedTypes != 0 { sizeswg.Add(1) go func() { - var sizes types.Sizes - sizes, sizeserr = packagesdriver.GetSizesGolist(ctx, state.cfgInvocation(), cfg.gocmdRunner) - // types.SizesFor always returns nil or a *types.StdSizes. - response.dr.Sizes, _ = sizes.(*types.StdSizes) + compiler, arch, err := packagesdriver.GetSizesForArgsGolist(ctx, state.cfgInvocation(), cfg.gocmdRunner) + sizeserr = err + response.dr.Compiler = compiler + response.dr.Arch = arch sizeswg.Done() }() } @@ -1110,7 +1108,7 @@ func (state *golistState) writeOverlays() (filename string, cleanup func(), err if len(state.cfg.Overlay) == 0 { return "", func() {}, nil } - dir, err := ioutil.TempDir("", "gopackages-*") + dir, err := os.MkdirTemp("", "gopackages-*") if err != nil { return "", nil, err } @@ -1129,7 +1127,7 @@ func (state *golistState) writeOverlays() (filename string, cleanup func(), err // Create a unique filename for the overlaid files, to avoid // creating nested directories. noSeparator := strings.Join(strings.Split(filepath.ToSlash(k), "/"), "") - f, err := ioutil.TempFile(dir, fmt.Sprintf("*-%s", noSeparator)) + f, err := os.CreateTemp(dir, fmt.Sprintf("*-%s", noSeparator)) if err != nil { return "", func() {}, err } @@ -1147,7 +1145,7 @@ func (state *golistState) writeOverlays() (filename string, cleanup func(), err } // Write out the overlay file that contains the filepath mappings. filename = filepath.Join(dir, "overlay.json") - if err := ioutil.WriteFile(filename, b, 0665); err != nil { + if err := os.WriteFile(filename, b, 0665); err != nil { return "", func() {}, err } return filename, cleanup, nil diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go index da1a27eea6..ece0e7c603 100644 --- a/vendor/golang.org/x/tools/go/packages/packages.go +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -16,7 +16,6 @@ import ( "go/token" "go/types" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -220,8 +219,10 @@ type driverResponse struct { // lists of multiple drivers, go/packages will fall back to the next driver. NotHandled bool - // Sizes, if not nil, is the types.Sizes to use when type checking. - Sizes *types.StdSizes + // Compiler and Arch are the arguments pass of types.SizesFor + // to get a types.Sizes to use when type checking. + Compiler string + Arch string // Roots is the set of package IDs that make up the root packages. // We have to encode this separately because when we encode a single package @@ -262,7 +263,7 @@ func Load(cfg *Config, patterns ...string) ([]*Package, error) { if err != nil { return nil, err } - l.sizes = response.Sizes + l.sizes = types.SizesFor(response.Compiler, response.Arch) return l.refine(response) } @@ -1125,7 +1126,7 @@ func (ld *loader) parseFile(filename string) (*ast.File, error) { var err error if src == nil { ioLimit <- true // wait - src, err = ioutil.ReadFile(filename) + src, err = os.ReadFile(filename) <-ioLimit // signal } if err != nil { diff --git a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go index c725d839ba..fa5834baf7 100644 --- a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go +++ b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go @@ -32,6 +32,7 @@ import ( _ "unsafe" "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/typesinternal" ) // A Path is an opaque name that identifies a types.Object @@ -127,12 +128,15 @@ type Encoder struct { skipMethodSorting bool } -// Exposed to gopls via golang.org/x/tools/internal/typesinternal -// TODO(golang/go#61443): eliminate this parameter one way or the other. +// Expose back doors so that gopls can avoid method sorting, which can dominate +// analysis on certain repositories. // -//go:linkname skipMethodSorting -func skipMethodSorting(enc *Encoder) { - enc.skipMethodSorting = true +// TODO(golang/go#61443): remove this. +func init() { + typesinternal.SkipEncoderMethodSorting = func(enc interface{}) { + enc.(*Encoder).skipMethodSorting = true + } + typesinternal.ObjectpathObject = object } // For returns the path to an object relative to its package, @@ -572,17 +576,16 @@ func findTypeParam(obj types.Object, list *typeparams.TypeParamList, path []byte // Object returns the object denoted by path p within the package pkg. func Object(pkg *types.Package, p Path) (types.Object, error) { - return object(pkg, p, false) + return object(pkg, string(p), false) } // Note: the skipMethodSorting parameter must match the value of // Encoder.skipMethodSorting used during encoding. -func object(pkg *types.Package, p Path, skipMethodSorting bool) (types.Object, error) { - if p == "" { +func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.Object, error) { + if pathstr == "" { return nil, fmt.Errorf("empty path") } - pathstr := string(p) var pkgobj, suffix string if dot := strings.IndexByte(pathstr, opType); dot < 0 { pkgobj = pathstr diff --git a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go index b1223713b9..2d078ccb19 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go @@ -29,7 +29,6 @@ import ( "go/token" "go/types" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -221,7 +220,7 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func switch hdr { case "$$B\n": var data []byte - data, err = ioutil.ReadAll(buf) + data, err = io.ReadAll(buf) if err != nil { break } diff --git a/vendor/golang.org/x/tools/internal/typeparams/coretype.go b/vendor/golang.org/x/tools/internal/typeparams/coretype.go index 993135ec90..71248209ee 100644 --- a/vendor/golang.org/x/tools/internal/typeparams/coretype.go +++ b/vendor/golang.org/x/tools/internal/typeparams/coretype.go @@ -81,13 +81,13 @@ func CoreType(T types.Type) types.Type { // restrictions may be arbitrarily complex. For example, consider the // following: // -// type A interface{ ~string|~[]byte } +// type A interface{ ~string|~[]byte } // -// type B interface{ int|string } +// type B interface{ int|string } // -// type C interface { ~string|~int } +// type C interface { ~string|~int } // -// type T[P interface{ A|B; C }] int +// type T[P interface{ A|B; C }] int // // In this example, the structural type restriction of P is ~string|int: A|B // expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, diff --git a/vendor/golang.org/x/tools/internal/typeparams/termlist.go b/vendor/golang.org/x/tools/internal/typeparams/termlist.go index 933106a23d..cbd12f8013 100644 --- a/vendor/golang.org/x/tools/internal/typeparams/termlist.go +++ b/vendor/golang.org/x/tools/internal/typeparams/termlist.go @@ -30,7 +30,7 @@ func (xl termlist) String() string { var buf bytes.Buffer for i, x := range xl { if i > 0 { - buf.WriteString(" ∪ ") + buf.WriteString(" | ") } buf.WriteString(x.String()) } diff --git a/vendor/golang.org/x/tools/internal/typeparams/typeterm.go b/vendor/golang.org/x/tools/internal/typeparams/typeterm.go index 7ddee28d98..7350bb702a 100644 --- a/vendor/golang.org/x/tools/internal/typeparams/typeterm.go +++ b/vendor/golang.org/x/tools/internal/typeparams/typeterm.go @@ -10,11 +10,10 @@ import "go/types" // A term describes elementary type sets: // -// ∅: (*term)(nil) == ∅ // set of no types (empty set) -// 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse) -// T: &term{false, T} == {T} // set of type T -// ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t -// +// ∅: (*term)(nil) == ∅ // set of no types (empty set) +// 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse) +// T: &term{false, T} == {T} // set of type T +// ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t type term struct { tilde bool // valid if typ != nil typ types.Type diff --git a/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go b/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go new file mode 100644 index 0000000000..5e96e89557 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go @@ -0,0 +1,24 @@ +// Copyright 2023 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 typesinternal + +import "go/types" + +// This file contains back doors that allow gopls to avoid method sorting when +// using the objectpath package. +// +// This is performance-critical in certain repositories, but changing the +// behavior of the objectpath package is still being discussed in +// golang/go#61443. If we decide to remove the sorting in objectpath we can +// simply delete these back doors. Otherwise, we should add a new API to +// objectpath that allows controlling the sorting. + +// SkipEncoderMethodSorting marks enc (which must be an *objectpath.Encoder) as +// not requiring sorted methods. +var SkipEncoderMethodSorting func(enc interface{}) + +// ObjectpathObject is like objectpath.Object, but allows suppressing method +// sorting. +var ObjectpathObject func(pkg *types.Package, p string, skipMethodSorting bool) (types.Object, error) diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go index 66e8b099bd..ce7d4351b2 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/types.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -11,8 +11,6 @@ import ( "go/types" "reflect" "unsafe" - - "golang.org/x/tools/go/types/objectpath" ) func SetUsesCgo(conf *types.Config) bool { @@ -52,17 +50,3 @@ func ReadGo116ErrorData(err types.Error) (code ErrorCode, start, end token.Pos, } var SetGoVersion = func(conf *types.Config, version string) bool { return false } - -// SkipEncoderMethodSorting marks the encoder as not requiring sorted methods, -// as an optimization for gopls (which guarantees the order of parsed source files). -// -// TODO(golang/go#61443): eliminate this parameter one way or the other. -// -//go:linkname SkipEncoderMethodSorting golang.org/x/tools/go/types/objectpath.skipMethodSorting -func SkipEncoderMethodSorting(enc *objectpath.Encoder) - -// ObjectpathObject is like objectpath.Object, but allows suppressing method -// sorting (which is not necessary for gopls). -// -//go:linkname ObjectpathObject golang.org/x/tools/go/types/objectpath.object -func ObjectpathObject(pkg *types.Package, p objectpath.Path, skipMethodSorting bool) (types.Object, error) diff --git a/vendor/k8s.io/cloud-provider/api/retry_error.go b/vendor/k8s.io/cloud-provider/api/retry_error.go new file mode 100644 index 0000000000..ac0e5e6e72 --- /dev/null +++ b/vendor/k8s.io/cloud-provider/api/retry_error.go @@ -0,0 +1,46 @@ +/* +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 api + +import ( + "time" +) + +// RetryError indicates that a service reconciliation should be retried after a +// fixed duration (as opposed to backing off exponentially). +type RetryError struct { + msg string + retryAfter time.Duration +} + +// NewRetryError returns a RetryError. +func NewRetryError(msg string, retryAfter time.Duration) *RetryError { + return &RetryError{ + msg: msg, + retryAfter: retryAfter, + } +} + +// Error shows the details of the retry reason. +func (re *RetryError) Error() string { + return re.msg +} + +// RetryAfter returns the defined retry-after duration. +func (re *RetryError) RetryAfter() time.Duration { + return re.retryAfter +} diff --git a/vendor/k8s.io/cloud-provider/api/well_known_annotations.go b/vendor/k8s.io/cloud-provider/api/well_known_annotations.go new file mode 100644 index 0000000000..fd03ea0a02 --- /dev/null +++ b/vendor/k8s.io/cloud-provider/api/well_known_annotations.go @@ -0,0 +1,26 @@ +/* +Copyright 2017 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 api + +const ( + // AnnotationAlphaProvidedIPAddr is a node IP annotation set by the "external" cloud provider. + // When kubelet is started with the "external" cloud provider, then + // it sets this annotation on the node to denote an ip address set from the + // cmd line flag (--node-ip). This ip is verified with the cloudprovider as valid by + // the cloud-controller-manager + AnnotationAlphaProvidedIPAddr = "alpha.kubernetes.io/provided-node-ip" +) diff --git a/vendor/k8s.io/cloud-provider/api/well_known_taints.go b/vendor/k8s.io/cloud-provider/api/well_known_taints.go new file mode 100644 index 0000000000..765bf2260b --- /dev/null +++ b/vendor/k8s.io/cloud-provider/api/well_known_taints.go @@ -0,0 +1,28 @@ +/* +Copyright 2015 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 api + +const ( + // TaintExternalCloudProvider sets this taint on a node to mark it as unusable, + // when kubelet is started with the "external" cloud provider, until a controller + // from the cloud-controller-manager intitializes this node, and then removes + // the taint + TaintExternalCloudProvider = "node.cloudprovider.kubernetes.io/uninitialized" + + // TaintNodeShutdown when node is shutdown in external cloud provider + TaintNodeShutdown = "node.cloudprovider.kubernetes.io/shutdown" +) diff --git a/vendor/k8s.io/cloud-provider/node/helpers/address.go b/vendor/k8s.io/cloud-provider/node/helpers/address.go new file mode 100644 index 0000000000..41112cdaeb --- /dev/null +++ b/vendor/k8s.io/cloud-provider/node/helpers/address.go @@ -0,0 +1,146 @@ +/* +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 helpers + +import ( + "fmt" + "net" + + "k8s.io/api/core/v1" + nodeutil "k8s.io/component-helpers/node/util" + netutils "k8s.io/utils/net" +) + +// AddToNodeAddresses appends the NodeAddresses to the passed-by-pointer slice, +// only if they do not already exist +func AddToNodeAddresses(addresses *[]v1.NodeAddress, addAddresses ...v1.NodeAddress) { + for _, add := range addAddresses { + exists := false + for _, existing := range *addresses { + if existing.Address == add.Address && existing.Type == add.Type { + exists = true + break + } + } + if !exists { + *addresses = append(*addresses, add) + } + } +} + +// GetNodeAddressesFromNodeIPLegacy filters node addresses to prefer a specific node IP or +// address family. This function is used only with legacy cloud providers. +// +// If nodeIP is either '0.0.0.0' or '::' it is taken to represent any address of +// that address family: IPv4 or IPv6. i.e. if nodeIP is '0.0.0.0' we will return +// node addresses sorted such that all IPv4 addresses are listed before IPv6 +// addresses. +// +// If nodeIP is a specific IP, either IPv4 or IPv6, we will return node +// addresses filtered such that: +// - Any address matching nodeIP will be listed first. +// - If nodeIP matches an address of a particular type (internal or external), +// that will be the *only* address of that type returned. +// - All remaining addresses are listed after. +func GetNodeAddressesFromNodeIPLegacy(nodeIP net.IP, cloudNodeAddresses []v1.NodeAddress) ([]v1.NodeAddress, error) { + // If nodeIP is unset, just use the addresses provided by the cloud provider as-is + if nodeIP == nil { + return cloudNodeAddresses, nil + } + + // nodeIP is "0.0.0.0" or "::"; sort cloudNodeAddresses to + // prefer addresses of the matching family + if nodeIP.IsUnspecified() { + preferIPv4 := nodeIP.To4() != nil + isPreferredIPFamily := func(ip net.IP) bool { return (ip.To4() != nil) == preferIPv4 } + + sortedAddresses := make([]v1.NodeAddress, 0, len(cloudNodeAddresses)) + for _, nodeAddress := range cloudNodeAddresses { + ip := netutils.ParseIPSloppy(nodeAddress.Address) + if ip == nil || isPreferredIPFamily(ip) { + sortedAddresses = append(sortedAddresses, nodeAddress) + } + } + for _, nodeAddress := range cloudNodeAddresses { + ip := netutils.ParseIPSloppy(nodeAddress.Address) + if ip != nil && !isPreferredIPFamily(ip) { + sortedAddresses = append(sortedAddresses, nodeAddress) + } + } + return sortedAddresses, nil + } + + // Otherwise the result is the same as for GetNodeAddressesFromNodeIP + return GetNodeAddressesFromNodeIP(nodeIP.String(), cloudNodeAddresses, false) +} + +// GetNodeAddressesFromNodeIP filters the provided list of nodeAddresses to match the +// providedNodeIP from the Node annotation (which is assumed to be non-empty). This is +// used for external cloud providers. +// +// It will return node addresses filtered such that: +// - Any address matching nodeIP will be listed first. +// - If nodeIP matches an address of a particular type (internal or external), +// that will be the *only* address of that type returned. +// - All remaining addresses are listed after. +// +// (This does not have the same behavior with `0.0.0.0` and `::` as +// GetNodeAddressesFromNodeIPLegacy, because that case never occurs for external cloud +// providers, because kubelet does not set the `provided-node-ip` annotation in that +// case.) +func GetNodeAddressesFromNodeIP(providedNodeIP string, cloudNodeAddresses []v1.NodeAddress, allowDualStack bool) ([]v1.NodeAddress, error) { + nodeIPs, err := nodeutil.ParseNodeIPAnnotation(providedNodeIP, allowDualStack) + if err != nil { + return nil, fmt.Errorf("failed to parse node IP %q: %v", providedNodeIP, err) + } + + enforcedNodeAddresses := []v1.NodeAddress{} + nodeIPTypes := make(map[v1.NodeAddressType]bool) + + for _, nodeIP := range nodeIPs { + // For every address supplied by the cloud provider that matches nodeIP, + // nodeIP is the enforced node address for that address Type (like + // InternalIP and ExternalIP), meaning other addresses of the same Type + // are discarded. See #61921 for more information: some cloud providers + // may supply secondary IPs, so nodeIP serves as a way to ensure that the + // correct IPs show up on a Node object. + + matched := false + for _, nodeAddress := range cloudNodeAddresses { + if netutils.ParseIPSloppy(nodeAddress.Address).Equal(nodeIP) { + enforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: nodeAddress.Type, Address: nodeAddress.Address}) + nodeIPTypes[nodeAddress.Type] = true + matched = true + } + } + + // nodeIP must be among the addresses supplied by the cloud provider + if !matched { + return nil, fmt.Errorf("failed to get node address from cloud provider that matches ip: %v", nodeIP) + } + } + + // Now use all other addresses supplied by the cloud provider NOT of the same Type + // as any nodeIP. + for _, nodeAddress := range cloudNodeAddresses { + if !nodeIPTypes[nodeAddress.Type] { + enforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: nodeAddress.Type, Address: nodeAddress.Address}) + } + } + + return enforcedNodeAddresses, nil +} diff --git a/vendor/k8s.io/cloud-provider/node/helpers/labels.go b/vendor/k8s.io/cloud-provider/node/helpers/labels.go new file mode 100644 index 0000000000..2a6e1bd974 --- /dev/null +++ b/vendor/k8s.io/cloud-provider/node/helpers/labels.go @@ -0,0 +1,103 @@ +/* +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 helpers + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/strategicpatch" + "k8s.io/apimachinery/pkg/util/wait" + clientset "k8s.io/client-go/kubernetes" + clientretry "k8s.io/client-go/util/retry" + "k8s.io/klog/v2" +) + +var updateLabelBackoff = wait.Backoff{ + Steps: 5, + Duration: 100 * time.Millisecond, + Jitter: 1.0, +} + +// AddOrUpdateLabelsOnNode updates the labels on the node and returns true on +// success and false on failure. +func AddOrUpdateLabelsOnNode(kubeClient clientset.Interface, labelsToUpdate map[string]string, node *v1.Node) bool { + err := addOrUpdateLabelsOnNode(kubeClient, node.Name, labelsToUpdate) + if err != nil { + utilruntime.HandleError( + fmt.Errorf( + "unable to update labels %+v for Node %q: %v", + labelsToUpdate, + node.Name, + err)) + return false + } + + klog.V(4).Infof("Updated labels %+v to Node %v", labelsToUpdate, node.Name) + return true +} + +func addOrUpdateLabelsOnNode(kubeClient clientset.Interface, nodeName string, labelsToUpdate map[string]string) error { + firstTry := true + return clientretry.RetryOnConflict(updateLabelBackoff, func() error { + var err error + var node *v1.Node + // First we try getting node from the API server cache, as it's cheaper. If it fails + // we get it from etcd to be sure to have fresh data. + if firstTry { + node, err = kubeClient.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{ResourceVersion: "0"}) + firstTry = false + } else { + node, err = kubeClient.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{}) + } + if err != nil { + return err + } + + // Make a copy of the node and update the labels. + newNode := node.DeepCopy() + if newNode.Labels == nil { + newNode.Labels = make(map[string]string) + } + for key, value := range labelsToUpdate { + newNode.Labels[key] = value + } + + oldData, err := json.Marshal(node) + if err != nil { + return fmt.Errorf("failed to marshal the existing node %#v: %v", node, err) + } + newData, err := json.Marshal(newNode) + if err != nil { + return fmt.Errorf("failed to marshal the new node %#v: %v", newNode, err) + } + patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, &v1.Node{}) + if err != nil { + return fmt.Errorf("failed to create a two-way merge patch: %v", err) + } + if _, err := kubeClient.CoreV1().Nodes().Patch(context.TODO(), node.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil { + return fmt.Errorf("failed to patch the node: %v", err) + } + return nil + }) +} diff --git a/vendor/k8s.io/cloud-provider/node/helpers/taints.go b/vendor/k8s.io/cloud-provider/node/helpers/taints.go new file mode 100644 index 0000000000..fb15d64bd2 --- /dev/null +++ b/vendor/k8s.io/cloud-provider/node/helpers/taints.go @@ -0,0 +1,245 @@ +/* +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. +*/ + +/* + +NOTE: the contents of this file has been copied from k8s.io/kubernetes/pkg/controller +and k8s.io/kubernetes/pkg/util/taints. The reason for duplicating this code is to remove +dependencies to k8s.io/kubernetes in all the cloud providers. Once k8s.io/kubernetes/pkg/util/taints +is moved to an external repository, this file should be removed and replaced with that one. +*/ + +package helpers + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/strategicpatch" + "k8s.io/apimachinery/pkg/util/wait" + clientset "k8s.io/client-go/kubernetes" + clientretry "k8s.io/client-go/util/retry" +) + +var updateTaintBackoff = wait.Backoff{ + Steps: 5, + Duration: 100 * time.Millisecond, + Jitter: 1.0, +} + +// AddOrUpdateTaintOnNode add taints to the node. If taint was added into node, it'll issue API calls +// to update nodes; otherwise, no API calls. Return error if any. +func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taints ...*v1.Taint) error { + if len(taints) == 0 { + return nil + } + firstTry := true + return clientretry.RetryOnConflict(updateTaintBackoff, func() error { + var err error + var oldNode *v1.Node + // First we try getting node from the API server cache, as it's cheaper. If it fails + // we get it from etcd to be sure to have fresh data. + if firstTry { + oldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{ResourceVersion: "0"}) + firstTry = false + } else { + oldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{}) + } + if err != nil { + return err + } + + var newNode *v1.Node + oldNodeCopy := oldNode + updated := false + for _, taint := range taints { + curNewNode, ok, err := addOrUpdateTaint(oldNodeCopy, taint) + if err != nil { + return fmt.Errorf("failed to update taint of node") + } + updated = updated || ok + newNode = curNewNode + oldNodeCopy = curNewNode + } + if !updated { + return nil + } + return PatchNodeTaints(c, nodeName, oldNode, newNode) + }) +} + +// PatchNodeTaints patches node's taints. +func PatchNodeTaints(c clientset.Interface, nodeName string, oldNode *v1.Node, newNode *v1.Node) error { + // Strip base diff node from RV to ensure that our Patch request will set RV to check for conflicts over .spec.taints. + // This is needed because .spec.taints does not specify patchMergeKey and patchStrategy and adding them is no longer an option for compatibility reasons. + // Using other Patch strategy works for adding new taints, however will not resolve problem with taint removal. + oldNodeNoRV := oldNode.DeepCopy() + oldNodeNoRV.ResourceVersion = "" + oldDataNoRV, err := json.Marshal(&oldNodeNoRV) + if err != nil { + return fmt.Errorf("failed to marshal old node %#v for node %q: %v", oldNodeNoRV, nodeName, err) + } + + newTaints := newNode.Spec.Taints + newNodeClone := oldNode.DeepCopy() + newNodeClone.Spec.Taints = newTaints + newData, err := json.Marshal(newNodeClone) + if err != nil { + return fmt.Errorf("failed to marshal new node %#v for node %q: %v", newNodeClone, nodeName, err) + } + + patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldDataNoRV, newData, v1.Node{}) + if err != nil { + return fmt.Errorf("failed to create patch for node %q: %v", nodeName, err) + } + + _, err = c.CoreV1().Nodes().Patch(context.TODO(), nodeName, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}) + return err +} + +// addOrUpdateTaint tries to add a taint to annotations list. Returns a new copy of updated Node and true if something was updated +// false otherwise. +func addOrUpdateTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error) { + newNode := node.DeepCopy() + nodeTaints := newNode.Spec.Taints + + var newTaints []v1.Taint + updated := false + for i := range nodeTaints { + if taint.MatchTaint(&nodeTaints[i]) { + if equality.Semantic.DeepEqual(*taint, nodeTaints[i]) { + return newNode, false, nil + } + newTaints = append(newTaints, *taint) + updated = true + continue + } + + newTaints = append(newTaints, nodeTaints[i]) + } + + if !updated { + newTaints = append(newTaints, *taint) + } + + newNode.Spec.Taints = newTaints + return newNode, true, nil +} + +// RemoveTaintOffNode is for cleaning up taints temporarily added to node, +// won't fail if target taint doesn't exist or has been removed. +// If passed a node it'll check if there's anything to be done, if taint is not present it won't issue +// any API calls. +func RemoveTaintOffNode(c clientset.Interface, nodeName string, node *v1.Node, taints ...*v1.Taint) error { + if len(taints) == 0 { + return nil + } + // Short circuit for limiting amount of API calls. + if node != nil { + match := false + for _, taint := range taints { + if taintExists(node.Spec.Taints, taint) { + match = true + break + } + } + if !match { + return nil + } + } + + firstTry := true + return clientretry.RetryOnConflict(updateTaintBackoff, func() error { + var err error + var oldNode *v1.Node + // First we try getting node from the API server cache, as it's cheaper. If it fails + // we get it from etcd to be sure to have fresh data. + if firstTry { + oldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{ResourceVersion: "0"}) + firstTry = false + } else { + oldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{}) + } + if err != nil { + return err + } + + var newNode *v1.Node + oldNodeCopy := oldNode + updated := false + for _, taint := range taints { + curNewNode, ok, err := removeTaint(oldNodeCopy, taint) + if err != nil { + return fmt.Errorf("failed to remove taint of node") + } + updated = updated || ok + newNode = curNewNode + oldNodeCopy = curNewNode + } + if !updated { + return nil + } + return PatchNodeTaints(c, nodeName, oldNode, newNode) + }) +} + +// taintExists checks if the given taint exists in list of taints. Returns true if exists false otherwise. +func taintExists(taints []v1.Taint, taintToFind *v1.Taint) bool { + for _, taint := range taints { + if taint.MatchTaint(taintToFind) { + return true + } + } + return false +} + +// removeTaint tries to remove a taint from annotations list. Returns a new copy of updated Node and true if something was updated +// false otherwise. +func removeTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error) { + newNode := node.DeepCopy() + nodeTaints := newNode.Spec.Taints + if len(nodeTaints) == 0 { + return newNode, false, nil + } + + if !taintExists(nodeTaints, taint) { + return newNode, false, nil + } + + newTaints, _ := deleteTaint(nodeTaints, taint) + newNode.Spec.Taints = newTaints + return newNode, true, nil +} + +// deleteTaint removes all the taints that have the same key and effect to given taintToDelete. +func deleteTaint(taints []v1.Taint, taintToDelete *v1.Taint) ([]v1.Taint, bool) { + newTaints := []v1.Taint{} + deleted := false + for i := range taints { + if taintToDelete.MatchTaint(&taints[i]) { + deleted = true + continue + } + newTaints = append(newTaints, taints[i]) + } + return newTaints, deleted +} diff --git a/vendor/k8s.io/component-helpers/node/util/cidr.go b/vendor/k8s.io/component-helpers/node/util/cidr.go new file mode 100644 index 0000000000..4d626ee004 --- /dev/null +++ b/vendor/k8s.io/component-helpers/node/util/cidr.go @@ -0,0 +1,58 @@ +/* +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 util + +import ( + "context" + "encoding/json" + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + clientset "k8s.io/client-go/kubernetes" + "k8s.io/klog/v2" +) + +type nodeForCIDRMergePatch struct { + Spec nodeSpecForMergePatch `json:"spec"` +} + +type nodeSpecForMergePatch struct { + PodCIDR string `json:"podCIDR"` + PodCIDRs []string `json:"podCIDRs,omitempty"` +} + +// PatchNodeCIDRs patches the specified node.CIDR=cidrs[0] and node.CIDRs to the given value. +func PatchNodeCIDRs(c clientset.Interface, node types.NodeName, cidrs []string) error { + // set the pod cidrs list and set the old pod cidr field + patch := nodeForCIDRMergePatch{ + Spec: nodeSpecForMergePatch{ + PodCIDR: cidrs[0], + PodCIDRs: cidrs, + }, + } + + patchBytes, err := json.Marshal(&patch) + if err != nil { + return fmt.Errorf("failed to json.Marshal CIDR: %v", err) + } + klog.V(4).Infof("cidrs patch bytes are:%s", string(patchBytes)) + if _, err := c.CoreV1().Nodes().Patch(context.TODO(), string(node), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil { + return fmt.Errorf("failed to patch node CIDR: %v", err) + } + return nil +} diff --git a/vendor/k8s.io/component-helpers/node/util/conditions.go b/vendor/k8s.io/component-helpers/node/util/conditions.go new file mode 100644 index 0000000000..3ad4dda891 --- /dev/null +++ b/vendor/k8s.io/component-helpers/node/util/conditions.go @@ -0,0 +1,57 @@ +/* +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 util + +import ( + "context" + "encoding/json" + "time" + + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + clientset "k8s.io/client-go/kubernetes" +) + +// GetNodeCondition extracts the provided condition from the given status and returns that. +// Returns nil and -1 if the condition is not present, and the index of the located condition. +func GetNodeCondition(status *v1.NodeStatus, conditionType v1.NodeConditionType) (int, *v1.NodeCondition) { + if status == nil { + return -1, nil + } + for i := range status.Conditions { + if status.Conditions[i].Type == conditionType { + return i, &status.Conditions[i] + } + } + return -1, nil +} + +// SetNodeCondition updates specific node condition with patch operation. +func SetNodeCondition(c clientset.Interface, node types.NodeName, condition v1.NodeCondition) error { + condition.LastHeartbeatTime = metav1.NewTime(time.Now()) + patch, err := json.Marshal(map[string]interface{}{ + "status": map[string]interface{}{ + "conditions": []v1.NodeCondition{condition}, + }, + }) + if err != nil { + return err + } + _, err = c.CoreV1().Nodes().PatchStatus(context.TODO(), string(node), patch) + return err +} diff --git a/vendor/k8s.io/component-helpers/node/util/hostname.go b/vendor/k8s.io/component-helpers/node/util/hostname.go new file mode 100644 index 0000000000..15d62c0ba5 --- /dev/null +++ b/vendor/k8s.io/component-helpers/node/util/hostname.go @@ -0,0 +1,46 @@ +/* +Copyright 2015 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 util + +import ( + "fmt" + "os" + "strings" +) + +// GetHostname returns OS's hostname if 'hostnameOverride' is empty; otherwise, it returns +// 'hostnameOverride'. In either case, the value is canonicalized (trimmed and +// lowercased). +func GetHostname(hostnameOverride string) (string, error) { + hostName := hostnameOverride + if len(hostName) == 0 { + nodeName, err := os.Hostname() + if err != nil { + return "", fmt.Errorf("couldn't determine hostname: %w", err) + } + hostName = nodeName + } + + // Trim whitespaces first to avoid getting an empty hostname + // For linux, the hostname is read from file /proc/sys/kernel/hostname directly + hostName = strings.TrimSpace(hostName) + if len(hostName) == 0 { + return "", fmt.Errorf("empty hostname is invalid") + } + + return strings.ToLower(hostName), nil +} diff --git a/vendor/k8s.io/component-helpers/node/util/ips.go b/vendor/k8s.io/component-helpers/node/util/ips.go new file mode 100644 index 0000000000..ff306a3dc3 --- /dev/null +++ b/vendor/k8s.io/component-helpers/node/util/ips.go @@ -0,0 +1,82 @@ +/* +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 util + +import ( + "fmt" + "net" + "strings" + + "k8s.io/klog/v2" + netutils "k8s.io/utils/net" +) + +const ( + cloudProviderNone = "" + cloudProviderExternal = "external" +) + +// parseNodeIP implements ParseNodeIPArgument and ParseNodeIPAnnotation +func parseNodeIP(nodeIP string, allowDual, sloppy bool) ([]net.IP, error) { + var nodeIPs []net.IP + if nodeIP != "" || !sloppy { + for _, ip := range strings.Split(nodeIP, ",") { + if sloppy { + ip = strings.TrimSpace(ip) + } + parsedNodeIP := netutils.ParseIPSloppy(ip) + if parsedNodeIP == nil { + if sloppy { + klog.InfoS("Could not parse node IP. Ignoring", "IP", ip) + } else { + return nil, fmt.Errorf("could not parse %q", ip) + } + } else { + nodeIPs = append(nodeIPs, parsedNodeIP) + } + } + } + + if len(nodeIPs) > 2 || (len(nodeIPs) == 2 && netutils.IsIPv6(nodeIPs[0]) == netutils.IsIPv6(nodeIPs[1])) { + return nil, fmt.Errorf("must contain either a single IP or a dual-stack pair of IPs") + } else if len(nodeIPs) == 2 && !allowDual { + return nil, fmt.Errorf("dual-stack not supported in this configuration") + } else if len(nodeIPs) == 2 && (nodeIPs[0].IsUnspecified() || nodeIPs[1].IsUnspecified()) { + return nil, fmt.Errorf("dual-stack node IP cannot include '0.0.0.0' or '::'") + } + + return nodeIPs, nil +} + +// ParseNodeIPArgument parses kubelet's --node-ip argument. If nodeIP contains invalid +// values, they will be logged and ignored. Dual-stack node IPs are allowed if +// cloudProvider is unset, or if it is `"external"` and allowCloudDualStack is true. +func ParseNodeIPArgument(nodeIP, cloudProvider string, allowCloudDualStack bool) ([]net.IP, error) { + var allowDualStack bool + if (cloudProvider == cloudProviderNone) || (cloudProvider == cloudProviderExternal && allowCloudDualStack) { + allowDualStack = true + } + return parseNodeIP(nodeIP, allowDualStack, true) +} + +// ParseNodeIPAnnotation parses the `alpha.kubernetes.io/provided-node-ip` annotation, +// which can be either a single IP address or (if allowDualStack is true) a +// comma-separated pair of IP addresses. Unlike with ParseNodeIPArgument, invalid values +// are considered an error. +func ParseNodeIPAnnotation(nodeIP string, allowDualStack bool) ([]net.IP, error) { + return parseNodeIP(nodeIP, allowDualStack, false) +} diff --git a/vendor/k8s.io/component-helpers/node/util/status.go b/vendor/k8s.io/component-helpers/node/util/status.go new file mode 100644 index 0000000000..a3666be310 --- /dev/null +++ b/vendor/k8s.io/component-helpers/node/util/status.go @@ -0,0 +1,134 @@ +/* +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 util + +import ( + "context" + "encoding/json" + "fmt" + + v1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/strategicpatch" + v1core "k8s.io/client-go/kubernetes/typed/core/v1" +) + +// PatchNodeStatus patches node status. +func PatchNodeStatus(c v1core.CoreV1Interface, nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) (*v1.Node, []byte, error) { + patchBytes, err := preparePatchBytesforNodeStatus(nodeName, oldNode, newNode) + if err != nil { + return nil, nil, err + } + + updatedNode, err := c.Nodes().Patch(context.TODO(), string(nodeName), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, "status") + if err != nil { + return nil, nil, fmt.Errorf("failed to patch status %q for node %q: %v", patchBytes, nodeName, err) + } + return updatedNode, patchBytes, nil +} + +func preparePatchBytesforNodeStatus(nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) ([]byte, error) { + oldData, err := json.Marshal(oldNode) + if err != nil { + return nil, fmt.Errorf("failed to Marshal oldData for node %q: %v", nodeName, err) + } + + // NodeStatus.Addresses is incorrectly annotated as patchStrategy=merge, which + // will cause strategicpatch.CreateTwoWayMergePatch to create an incorrect patch + // if it changed. + manuallyPatchAddresses := (len(oldNode.Status.Addresses) > 0) && !equality.Semantic.DeepEqual(oldNode.Status.Addresses, newNode.Status.Addresses) + + // Reset spec to make sure only patch for Status or ObjectMeta is generated. + // Note that we don't reset ObjectMeta here, because: + // 1. This aligns with Nodes().UpdateStatus(). + // 2. Some component does use this to update node annotations. + diffNode := newNode.DeepCopy() + diffNode.Spec = oldNode.Spec + if manuallyPatchAddresses { + diffNode.Status.Addresses = oldNode.Status.Addresses + } + newData, err := json.Marshal(diffNode) + if err != nil { + return nil, fmt.Errorf("failed to Marshal newData for node %q: %v", nodeName, err) + } + + patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{}) + if err != nil { + return nil, fmt.Errorf("failed to CreateTwoWayMergePatch for node %q: %v", nodeName, err) + } + if manuallyPatchAddresses { + patchBytes, err = fixupPatchForNodeStatusAddresses(patchBytes, newNode.Status.Addresses) + if err != nil { + return nil, fmt.Errorf("failed to fix up NodeAddresses in patch for node %q: %v", nodeName, err) + } + } + + return patchBytes, nil +} + +// fixupPatchForNodeStatusAddresses adds a replace-strategy patch for Status.Addresses to +// the existing patch +func fixupPatchForNodeStatusAddresses(patchBytes []byte, addresses []v1.NodeAddress) ([]byte, error) { + // Given patchBytes='{"status": {"conditions": [ ... ], "phase": ...}}' and + // addresses=[{"type": "InternalIP", "address": "10.0.0.1"}], we need to generate: + // + // { + // "status": { + // "conditions": [ ... ], + // "phase": ..., + // "addresses": [ + // { + // "type": "InternalIP", + // "address": "10.0.0.1" + // }, + // { + // "$patch": "replace" + // } + // ] + // } + // } + + var patchMap map[string]interface{} + if err := json.Unmarshal(patchBytes, &patchMap); err != nil { + return nil, err + } + + addrBytes, err := json.Marshal(addresses) + if err != nil { + return nil, err + } + var addrArray []interface{} + if err := json.Unmarshal(addrBytes, &addrArray); err != nil { + return nil, err + } + addrArray = append(addrArray, map[string]interface{}{"$patch": "replace"}) + + status := patchMap["status"] + if status == nil { + status = map[string]interface{}{} + patchMap["status"] = status + } + statusMap, ok := status.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("unexpected data in patch") + } + statusMap["addresses"] = addrArray + + return json.Marshal(patchMap) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 70dbccede0..5c7e8e0c7f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -45,9 +45,15 @@ github.com/Azure/azure-sdk-for-go/sdk/internal/uuid # github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.3.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 -# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.3.0 +# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry +# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 v4.4.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 +# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault v1.3.0 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault # github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 v4.3.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 @@ -57,6 +63,9 @@ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns # github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources +# github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.5.0 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage # github.com/Azure/go-autorest v14.2.0+incompatible ## explicit github.com/Azure/go-autorest @@ -155,14 +164,14 @@ github.com/docker/distribution/reference ## explicit; go 1.13 github.com/emicklei/go-restful/v3 github.com/emicklei/go-restful/v3/log -# github.com/evanphx/json-patch v5.6.0+incompatible +# github.com/evanphx/json-patch v5.7.0+incompatible ## explicit github.com/evanphx/json-patch -# github.com/felixge/httpsnoop v1.0.3 +# github.com/felixge/httpsnoop v1.0.4 ## explicit; go 1.13 github.com/felixge/httpsnoop -# github.com/fsnotify/fsnotify v1.6.0 -## explicit; go 1.16 +# github.com/fsnotify/fsnotify v1.7.0 +## explicit; go 1.17 github.com/fsnotify/fsnotify # github.com/go-logr/logr v1.3.0 ## explicit; go 1.18 @@ -254,7 +263,7 @@ github.com/google/gofuzz/bytesource # github.com/google/pprof v0.0.0-20230602010524-ada837c32108 ## explicit; go 1.19 github.com/google/pprof/profile -# github.com/google/uuid v1.3.1 +# github.com/google/uuid v1.4.0 ## explicit github.com/google/uuid # github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 @@ -332,7 +341,7 @@ github.com/modern-go/reflect2 # github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 ## explicit github.com/munnerz/goautoneg -# github.com/onsi/ginkgo/v2 v2.13.0 +# github.com/onsi/ginkgo/v2 v2.13.1 ## explicit; go 1.18 github.com/onsi/ginkgo/v2 github.com/onsi/ginkgo/v2/config @@ -354,7 +363,7 @@ github.com/onsi/ginkgo/v2/internal/parallel_support github.com/onsi/ginkgo/v2/internal/testingtproxy github.com/onsi/ginkgo/v2/reporters github.com/onsi/ginkgo/v2/types -# github.com/onsi/gomega v1.28.0 +# github.com/onsi/gomega v1.30.0 ## explicit; go 1.18 github.com/onsi/gomega github.com/onsi/gomega/format @@ -412,7 +421,7 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/spf13/cobra v1.7.0 +# github.com/spf13/cobra v1.8.0 ## explicit; go 1.15 github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 @@ -451,8 +460,8 @@ go.etcd.io/etcd/client/v3/internal/resolver ## explicit; go 1.20 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.45.0 -## explicit; go 1.19 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.0 +## explicit; go 1.20 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil # go.opentelemetry.io/otel v1.21.0 @@ -519,8 +528,8 @@ go.uber.org/zap/internal/color go.uber.org/zap/internal/exit go.uber.org/zap/zapcore go.uber.org/zap/zapgrpc -# golang.org/x/crypto v0.14.0 -## explicit; go 1.17 +# golang.org/x/crypto v0.15.0 +## explicit; go 1.18 golang.org/x/crypto/blowfish golang.org/x/crypto/chacha20 golang.org/x/crypto/cryptobyte @@ -540,8 +549,8 @@ golang.org/x/crypto/ssh/internal/bcrypt_pbkdf ## explicit; go 1.18 golang.org/x/exp/constraints golang.org/x/exp/slices -# golang.org/x/mod v0.12.0 -## explicit; go 1.17 +# golang.org/x/mod v0.13.0 +## explicit; go 1.18 golang.org/x/mod/semver # golang.org/x/net v0.17.0 ## explicit; go 1.17 @@ -562,8 +571,8 @@ golang.org/x/net/websocket ## explicit; go 1.18 golang.org/x/oauth2 golang.org/x/oauth2/internal -# golang.org/x/sync v0.4.0 -## explicit; go 1.17 +# golang.org/x/sync v0.5.0 +## explicit; go 1.18 golang.org/x/sync/errgroup golang.org/x/sync/singleflight # golang.org/x/sys v0.14.0 @@ -574,11 +583,11 @@ golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/term v0.13.0 -## explicit; go 1.17 +# golang.org/x/term v0.14.0 +## explicit; go 1.18 golang.org/x/term -# golang.org/x/text v0.13.0 -## explicit; go 1.17 +# golang.org/x/text v0.14.0 +## explicit; go 1.18 golang.org/x/text/encoding golang.org/x/text/encoding/charmap golang.org/x/text/encoding/htmlindex @@ -608,10 +617,10 @@ golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm golang.org/x/text/width -# golang.org/x/time v0.3.0 -## explicit +# golang.org/x/time v0.4.0 +## explicit; go 1.18 golang.org/x/time/rate -# golang.org/x/tools v0.12.0 +# golang.org/x/tools v0.14.0 ## explicit; go 1.18 golang.org/x/tools/cmd/stringer golang.org/x/tools/go/ast/inspector @@ -1295,6 +1304,7 @@ k8s.io/client-go/util/workqueue # k8s.io/cloud-provider v0.28.4 => k8s.io/cloud-provider v0.28.4 ## explicit; go 1.20 k8s.io/cloud-provider +k8s.io/cloud-provider/api k8s.io/cloud-provider/app/config k8s.io/cloud-provider/config k8s.io/cloud-provider/config/install @@ -1305,6 +1315,7 @@ k8s.io/cloud-provider/controllers/service/config k8s.io/cloud-provider/controllers/service/config/v1alpha1 k8s.io/cloud-provider/fake k8s.io/cloud-provider/names +k8s.io/cloud-provider/node/helpers k8s.io/cloud-provider/options k8s.io/cloud-provider/service/helpers k8s.io/cloud-provider/volume @@ -1334,6 +1345,7 @@ k8s.io/component-base/tracing/api/v1 k8s.io/component-base/version # k8s.io/component-helpers v0.28.4 => k8s.io/component-helpers v0.28.4 ## explicit; go 1.20 +k8s.io/component-helpers/node/util k8s.io/component-helpers/scheduling/corev1 k8s.io/component-helpers/scheduling/corev1/nodeaffinity k8s.io/component-helpers/storage/volume @@ -1389,7 +1401,7 @@ k8s.io/kube-openapi/pkg/validation/strfmt/bson ## explicit; go 1.20 k8s.io/kubectl/pkg/scale k8s.io/kubectl/pkg/util/podutils -# k8s.io/kubelet v0.28.0 => k8s.io/kubelet v0.28.4 +# k8s.io/kubelet v0.28.3 => k8s.io/kubelet v0.28.4 ## explicit; go 1.20 k8s.io/kubelet/pkg/apis # k8s.io/kubernetes v1.28.4 @@ -1488,7 +1500,7 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client -# sigs.k8s.io/cloud-provider-azure v1.27.1-0.20230825065334-8b1cf948b7ed +# sigs.k8s.io/cloud-provider-azure v1.27.1-0.20231127051539-860b1f095d2b ## explicit; go 1.20 sigs.k8s.io/cloud-provider-azure/pkg/azureclients sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient @@ -1535,16 +1547,22 @@ sigs.k8s.io/cloud-provider-azure/pkg/consts sigs.k8s.io/cloud-provider-azure/pkg/metrics sigs.k8s.io/cloud-provider-azure/pkg/provider 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/provider/virtualmachine sigs.k8s.io/cloud-provider-azure/pkg/retry sigs.k8s.io/cloud-provider-azure/pkg/util/deepcopy +sigs.k8s.io/cloud-provider-azure/pkg/util/taints sigs.k8s.io/cloud-provider-azure/pkg/version -# sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231012171618-1890d8703623 +# sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.0-20231127051539-860b1f095d2b ## explicit; go 1.20 sigs.k8s.io/cloud-provider-azure/pkg/azclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/deploymentclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/ipgroupclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient @@ -1555,20 +1573,27 @@ sigs.k8s.io/cloud-provider-azure/pkg/azclient/policy/retryrepectthrottled sigs.k8s.io/cloud-provider-azure/pkg/azclient/privateendpointclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatelinkserviceclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatezoneclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipprefixclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/resourcegroupclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/sshpublickeyresourceclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/subnetclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils/armbalancer +sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient +# sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.0-20231126174212-e5e88e755a1b +## explicit; go 1.20 +sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader # sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd ## explicit; go 1.18 sigs.k8s.io/json @@ -1580,9 +1605,10 @@ sigs.k8s.io/structured-merge-diff/v4/merge sigs.k8s.io/structured-merge-diff/v4/schema sigs.k8s.io/structured-merge-diff/v4/typed sigs.k8s.io/structured-merge-diff/v4/value -# sigs.k8s.io/yaml v1.3.0 +# sigs.k8s.io/yaml v1.4.0 ## explicit; go 1.12 sigs.k8s.io/yaml +sigs.k8s.io/yaml/goyaml.v2 # k8s.io/api => k8s.io/api v0.28.4 # k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.28.4 # k8s.io/apimachinery => k8s.io/apimachinery v0.28.4 diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/Makefile b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/Makefile index 74aec35680..44f00b3be3 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/Makefile +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/Makefile @@ -73,12 +73,13 @@ generate: install-dependencies build generatecode generateimpl vet-all .PHONY: generatecode generatecode: build ## Generate client $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v4 --package-alias armcontainerservice --resource ManagedCluster --client-name ManagedClustersClient --ratelimitkey containerServiceRateLimit + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry --package-alias armcontainerregistry --resource Registry --client-name RegistriesClient --verbs get,delete,listbyrg $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources --package-alias resources --resource Deployment --client-name DeploymentsClient --verbs delete --ratelimitkey deploymentRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources --package-alias resources --resource ResourceGroup --client-name ResourceGroupsClient $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource Disk --client-name DisksClient --ratelimitkey diskRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource AvailabilitySet --client-name AvailabilitySetsClient --verbs get,list --ratelimitkey availabilitySetRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource VirtualMachine --client-name VirtualMachinesClient --verbs createorupdate,delete,list --expand --ratelimitkey virtualMachineRateLimit - $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource VirtualMachineScaleSet --client-name VirtualMachineScaleSetsClient --verbs get,createorupdate,delete,list --ratelimitkey virtualMachineSizesRateLimit + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource VirtualMachineScaleSet --client-name VirtualMachineScaleSetsClient --verbs get,createorupdate,delete,list --ratelimitkey virtualMachineSizesRateLimit --expand $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource VirtualMachineScaleSet --subresource VirtualMachineScaleSetVM --client-name VirtualMachineScaleSetVMsClient --verbs get,delete,list $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource Snapshot --client-name SnapshotsClient --verbs get,createorupdate,delete --ratelimitkey snapshotRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 --package-alias armcompute --resource SSHPublicKeyResource --client-name SSHPublicKeysClient --verbs get,listbyrg @@ -89,12 +90,19 @@ generatecode: build ## Generate client $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource PrivateEndpoint --client-name PrivateEndpointsClient --verbs get,createorupdate --expand --ratelimitkey privateEndpointRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource PublicIPAddress --client-name PublicIPAddressesClient --verbs get,createorupdate,delete,list --expand --ratelimitkey publicIPAddressRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource PublicIPPrefix --client-name PublicIPPrefixesClient --verbs get,createorupdate,delete,list --expand - $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource RouteTable --client-name RouteTablesClient --verbs createorupdate,delete --ratelimitkey routeTableRateLimit + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource RouteTable --client-name RouteTablesClient --verbs get,createorupdate,delete,list --ratelimitkey routeTableRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource SecurityGroup --client-name SecurityGroupsClient --verbs get,createorupdate,delete,list --ratelimitkey securityGroupRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource PrivateLinkService --client-name PrivateLinkServicesClient --verbs get,createorupdate,delete,list --expand --ratelimitkey privateLinkServiceRateLimit $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4 --package-alias armnetwork --resource IPGroup --client-name IPGroupsClient --verbs get,createorupdate,delete,listbyrg --expand --ratelimitkey ipGroupRateLimit + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage --package-alias armstorage --resource Account --client-name AccountsClient --verbs listbyrg --expand $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns --package-alias armprivatedns --resource PrivateZone --client-name PrivateZonesClient --verbs get,createorupdate --ratelimitkey privateDNSRateLimit -## $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage --package-alias armstorage --resource FileShare --client-name FileSharesClient --expand + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage --package-alias armstorage --resource Account --subresource FileShare --client-name FileSharesClient --verbs get,createorupdate,delete,list + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage --package-alias armstorage --resource Account --subresource BlobContainer --client-name BlobContainersClient --verbs get,list + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage --package-alias armstorage --resource BlobServiceProperties --client-name BlobServicesClient + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault --package-alias armkeyvault --resource Vault --subresource Secret --client-name SecretsClient --verbs get,createorupdate,delete,list + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault --package-alias armkeyvault --resource Vault --client-name VaultsClient --verbs get,createorupdate,delete,list + $(TYPESCAFFOLD) --package github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources --package-alias armresources --resource Provider --client-name ProvidersClient + .PHONY: generateimpl generateimpl: build ## Generate client diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/custom.go new file mode 100644 index 0000000000..c94acad9aa --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/custom.go @@ -0,0 +1,62 @@ +/* +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 accountclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +func (client *Client) Create(ctx context.Context, resourceGroupName string, resourceName string, resource *armstorage.AccountCreateParameters) (*armstorage.Account, error) { + if resource == nil { + resource = &armstorage.AccountCreateParameters{} + } + resp, err := utils.NewPollerWrapper(client.AccountsClient.BeginCreate(ctx, resourceGroupName, resourceName, *resource, nil)).WaitforPollerResp(ctx) + if err != nil { + return nil, err + } + if resp != nil { + return &resp.Account, nil + } + return nil, nil +} + +func (client *Client) GetProperties(ctx context.Context, resourceGroupName string, accountName string, options *armstorage.AccountsClientGetPropertiesOptions) (*armstorage.Account, error) { + resp, err := client.AccountsClient.GetProperties(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.Account, nil +} + +// Delete deletes a Interface by name. +func (client *Client) Delete(ctx context.Context, resourceGroupName string, resourceName string) error { + _, err := client.AccountsClient.Delete(ctx, resourceGroupName, resourceName, nil) + return err +} + +func (client *Client) ListKeys(ctx context.Context, resourceGroupName string, accountName string) ([]*armstorage.AccountKey, error) { + resp, err := client.AccountsClient.ListKeys(ctx, resourceGroupName, accountName, nil) + if err != nil { + return nil, err + } + return resp.Keys, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/interface.go new file mode 100644 index 0000000000..9cc97b01ab --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/interface.go @@ -0,0 +1,35 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package accountclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// +azure:client:verbs=listbyrg,resource=Account,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage,packageAlias=armstorage,clientName=AccountsClient,expand=true +type Interface interface { + utils.ListFunc[armstorage.Account] + Create(ctx context.Context, resourceGroupName string, accountName string, resource *armstorage.AccountCreateParameters) (*armstorage.Account, error) + GetProperties(ctx context.Context, resourceGroupName string, accountName string, options *armstorage.AccountsClientGetPropertiesOptions) (*armstorage.Account, error) + Delete(ctx context.Context, resourceGroupName string, accountName string) error + ListKeys(ctx context.Context, resourceGroupName string, accountName string) ([]*armstorage.AccountKey, error) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/zz_generated_client.go new file mode 100644 index 0000000000..b7d29e3be5 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/zz_generated_client.go @@ -0,0 +1,57 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package accountclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armstorage.AccountsClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armstorage.NewAccountsClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +// List gets a list of Account in the resource group. +func (client *Client) List(ctx context.Context, resourceGroupName string) (result []*armstorage.Account, rerr error) { + pager := client.AccountsClient.NewListByResourceGroupPager(resourceGroupName, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/custom.go new file mode 100644 index 0000000000..f4268df08e --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/custom.go @@ -0,0 +1,49 @@ +/* +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 blobcontainerclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" +) + +// List gets a list of BlobContainer in the resource group. +func (client *Client) List(ctx context.Context, resourceGroupName string, parentResourceName string) (result []*armstorage.ListContainerItem, rerr error) { + pager := client.BlobContainersClient.NewListPager(resourceGroupName, parentResourceName, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} + +func (client *Client) CreateContainer(ctx context.Context, resourceGroupName, accountName, containerName string, parameters armstorage.BlobContainer) (*armstorage.BlobContainer, error) { + resp, err := client.BlobContainersClient.Create(ctx, resourceGroupName, accountName, containerName, parameters, nil) + if err != nil { + return nil, err + } + return &resp.BlobContainer, nil +} + +func (client *Client) DeleteContainer(ctx context.Context, resourceGroupName, accountName, containerName string) error { + _, err := client.BlobContainersClient.Delete(ctx, resourceGroupName, accountName, containerName, nil) + return err +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/interface.go new file mode 100644 index 0000000000..b8fc8ae9d4 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/interface.go @@ -0,0 +1,34 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package blobcontainerclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// +azure:client:verbs=get,resource=Account,subResource=BlobContainer,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage,packageAlias=armstorage,clientName=BlobContainersClient,expand=false +type Interface interface { + utils.SubResourceGetFunc[armstorage.BlobContainer] + CreateContainer(ctx context.Context, resourceGroupName, accountName, containerName string, parameters armstorage.BlobContainer) (*armstorage.BlobContainer, error) + DeleteContainer(ctx context.Context, resourceGroupName, accountName, containerName string) error + List(ctx context.Context, resourceGroupName string, parentResourceName string) (result []*armstorage.ListContainerItem, rerr error) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/zz_generated_client.go new file mode 100644 index 0000000000..91c6b49998 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/zz_generated_client.go @@ -0,0 +1,55 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package blobcontainerclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armstorage.BlobContainersClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armstorage.NewBlobContainersClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +// Get gets the BlobContainer +func (client *Client) Get(ctx context.Context, resourceGroupName string, parentResourceName string, resourceName string) (result *armstorage.BlobContainer, rerr error) { + + resp, err := client.BlobContainersClient.Get(ctx, resourceGroupName, parentResourceName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.BlobContainer, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/custom.go new file mode 100644 index 0000000000..42a8fab223 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/custom.go @@ -0,0 +1,42 @@ +/* +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 blobservicepropertiesclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" +) + +// Get gets the BlobServiceProperties +func (client *Client) Get(ctx context.Context, resourceGroupName string, resourceName string) (*armstorage.BlobServiceProperties, error) { + + resp, err := client.BlobServicesClient.GetServiceProperties(ctx, resourceGroupName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.BlobServiceProperties, nil +} + +func (client *Client) Set(ctx context.Context, resourceGroupName string, resourceName string, parameters armstorage.BlobServiceProperties) (*armstorage.BlobServiceProperties, error) { + resp, err := client.BlobServicesClient.SetServiceProperties(ctx, resourceGroupName, resourceName, parameters, nil) + if err != nil { + return nil, err + } + return &resp.BlobServiceProperties, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/interface.go new file mode 100644 index 0000000000..e70b1e8aa4 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/interface.go @@ -0,0 +1,30 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package blobservicepropertiesclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" +) + +// +azure:client:resource=BlobServiceProperties,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage,packageAlias=armstorage,clientName=BlobServicesClient,expand=false +type Interface interface { + Get(ctx context.Context, resourceGroupName string, resourceName string) (*armstorage.BlobServiceProperties, error) + Set(ctx context.Context, resourceGroupName string, resourceName string, parameters armstorage.BlobServiceProperties) (*armstorage.BlobServiceProperties, error) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/zz_generated_client.go new file mode 100644 index 0000000000..680cb52068 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient/zz_generated_client.go @@ -0,0 +1,42 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package blobservicepropertiesclient + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armstorage.BlobServicesClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armstorage.NewBlobServicesClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/LICENSE b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/LICENSE @@ -0,0 +1,202 @@ + + 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 + + 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. diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/config_loader.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/config_loader.go new file mode 100644 index 0000000000..a2b878f434 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/config_loader.go @@ -0,0 +1,25 @@ +/* +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 configloader + +import ( + "context" +) + +type ConfigLoader[Type any] interface { + Load(ctx context.Context) (*Type, error) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/load.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/load.go new file mode 100644 index 0000000000..350a46d8cb --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/load.go @@ -0,0 +1,82 @@ +/* +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 configloader + +import ( + "context" + "fmt" + "strings" + + clientset "k8s.io/client-go/kubernetes" +) + +type decoderFactory[Type any] func(content []byte, loader ConfigLoader[Type]) ConfigLoader[Type] +type K8sSecretLoaderConfig struct { + K8sSecretConfig + KubeClient clientset.Interface +} + +type FileLoaderConfig struct { + FilePath string +} + +// The config type for Azure cloud provider secret. Supported values are: +// * file : The values are read from local cloud-config file. +// * secret : The values from secret would override all configures from local cloud-config file. +// * merge : The values from secret would override only configurations that are explicitly set in the secret. This is the default value. +type CloudConfigType string + +const ( + CloudConfigTypeFile CloudConfigType = "file" + CloudConfigTypeSecret CloudConfigType = "secret" + CloudConfigTypeMerge CloudConfigType = "merge" +) + +type ConfigMergeConfig struct { + // The cloud configure type for Azure cloud provider. Supported values are file, secret and merge. + CloudConfigType CloudConfigType `json:"cloudConfigType,omitempty" yaml:"cloudConfigType,omitempty"` +} + +func Load[Type any](ctx context.Context, secretLoaderConfig *K8sSecretLoaderConfig, fileLoaderConfig *FileLoaderConfig) (*Type, error) { + + if fileLoaderConfig == nil { + return nil, fmt.Errorf("config file load config is nil") + } + //by default the config load type is merge + loadConfigloader := NewEmptyLoader[ConfigMergeConfig](&ConfigMergeConfig{CloudConfigType: CloudConfigTypeMerge}) + loadConfigloader = NewFileLoader(fileLoaderConfig.FilePath, loadConfigloader, NewYamlByteLoader[ConfigMergeConfig]) + loadConfig, err := loadConfigloader.Load(ctx) + if err != nil { + return nil, err + } + + configloader := NewFileLoader(fileLoaderConfig.FilePath, nil, NewYamlByteLoader[Type]) + if strings.EqualFold(string(loadConfig.CloudConfigType), string(CloudConfigTypeFile)) { + return configloader.Load(ctx) + } + + if secretLoaderConfig == nil { + return nil, fmt.Errorf("secret load config is nil") + } + + if strings.EqualFold(string(loadConfig.CloudConfigType), string(CloudConfigTypeSecret)) { + configloader = NewK8sSecretLoader(&secretLoaderConfig.K8sSecretConfig, secretLoaderConfig.KubeClient, nil, NewYamlByteLoader[Type]) + return configloader.Load(ctx) + } + configloader = NewK8sSecretLoader(&secretLoaderConfig.K8sSecretConfig, secretLoaderConfig.KubeClient, configloader, NewYamlByteLoader[Type]) + return configloader.Load(ctx) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_empty.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_empty.go new file mode 100644 index 0000000000..70b9ee0d58 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_empty.go @@ -0,0 +1,38 @@ +/* +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 configloader + +import ( + "context" +) + +type EmptyLoader[Type any] struct { + Data *Type +} + +func (e *EmptyLoader[Type]) Load(ctx context.Context) (*Type, error) { + return e.Data, nil +} + +func NewEmptyLoader[Type any](config *Type) ConfigLoader[Type] { + if config == nil { + config = new(Type) + } + return &EmptyLoader[Type]{ + Data: config, + } +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_file.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_file.go new file mode 100644 index 0000000000..bc33b0f9d1 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_file.go @@ -0,0 +1,63 @@ +/* +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 configloader + +import ( + "context" + "io" + "os" +) + +type FileLoader[Type any] struct { + filePath string + ConfigLoader[Type] + decoderFactory[Type] +} + +func NewFileLoader[Type any](filePath string, loader ConfigLoader[Type], decoder decoderFactory[Type]) ConfigLoader[Type] { + return &FileLoader[Type]{ + filePath: filePath, + ConfigLoader: loader, + decoderFactory: decoder, + } +} + +func (f *FileLoader[Type]) Load(ctx context.Context) (*Type, error) { + if f.ConfigLoader == nil { + f.ConfigLoader = NewEmptyLoader[Type](nil) + } + + var content []byte + if err := func() error { + file, err := os.Open(f.filePath) + if err != nil { + return err + } + defer file.Close() + + content, err = io.ReadAll(file) + if err != nil { + return err + } + return nil + }(); err != nil { + return nil, err + } + + loader := f.decoderFactory(content, f.ConfigLoader) + return loader.Load(ctx) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_secret.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_secret.go new file mode 100644 index 0000000000..b8cf9e5644 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_secret.go @@ -0,0 +1,100 @@ +/* +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 configloader + +import ( + "context" + "errors" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + clientset "k8s.io/client-go/kubernetes" +) + +type K8sSecretLoader[Type any] struct { + KubeClient clientset.Interface + ConfigLoader[Type] + *K8sSecretConfig + decoderFactory[Type] +} + +// cloud provider config secret +const ( + DefaultCloudProviderConfigSecName = "azure-cloud-provider" + DefaultCloudProviderConfigSecNamespace = "kube-system" + DefaultCloudProviderConfigSecKey = "cloud-config" +) + +var ( + ErrNoKubeClient = errors.New("no kube client provided") + ErrNoData = errors.New("no data in secret") +) + +type K8sSecretConfig struct { + SecretName string `json:"secretName,omitempty" yaml:"secretName,omitempty"` + SecretNamespace string `json:"secretNamespace,omitempty" yaml:"secretNamespace,omitempty"` + CloudConfigKey string `json:"cloudConfigKey,omitempty" yaml:"cloudConfigKey,omitempty"` +} + +func NewK8sSecretLoader[Type any](config *K8sSecretConfig, KubeClient kubernetes.Interface, loader ConfigLoader[Type], decoder decoderFactory[Type]) ConfigLoader[Type] { + if KubeClient == nil { + return nil + } + if config == nil { + return nil + } + if config.SecretName == "" { + config.SecretName = DefaultCloudProviderConfigSecName + } + if config.SecretNamespace == "" { + config.SecretNamespace = DefaultCloudProviderConfigSecNamespace + } + if config.CloudConfigKey == "" { + config.CloudConfigKey = DefaultCloudProviderConfigSecKey + } + return &K8sSecretLoader[Type]{ + ConfigLoader: loader, + K8sSecretConfig: config, + decoderFactory: decoder, + KubeClient: KubeClient, + } +} + +func (k *K8sSecretLoader[Type]) Load(ctx context.Context) (*Type, error) { + if k.ConfigLoader == nil { + k.ConfigLoader = NewEmptyLoader[Type](nil) + } + + if k.KubeClient == nil { + return nil, ErrNoKubeClient + } + + secret, err := k.KubeClient.CoreV1().Secrets(k.SecretNamespace).Get(ctx, k.SecretName, metav1.GetOptions{}) + if err != nil { + return nil, err + } + if len(secret.Data) <= 0 { + return nil, ErrNoData + } + var ok bool + var content []byte + if content, ok = secret.Data[k.CloudConfigKey]; !ok { + return nil, ErrNoData + } + loader := k.decoderFactory([]byte(content), k.ConfigLoader) + return loader.Load(ctx) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_yaml.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_yaml.go new file mode 100644 index 0000000000..5de8b4acc3 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader/loader_yaml.go @@ -0,0 +1,54 @@ +/* +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 configloader + +import ( + "bytes" + "context" + + "sigs.k8s.io/yaml" +) + +// YamlByteLoader is a FactoryConfigLoader that loads a YAML file from a byte array. +type YamlByteLoader[Type any] struct { + content []byte + ConfigLoader[Type] +} + +// Load loads the YAML file from the byte array and returns the client factory config. +func (s *YamlByteLoader[Type]) Load(ctx context.Context) (*Type, error) { + if s.ConfigLoader == nil { + s.ConfigLoader = NewEmptyLoader[Type](nil) + } + config, err := s.ConfigLoader.Load(ctx) + if err != nil { + return nil, err + } + s.content = bytes.TrimSpace(s.content) + if err := yaml.Unmarshal(bytes.TrimSpace(s.content), config); err != nil { + return nil, err + } + return config, nil +} + +// NewYamlByteLoader creates a YamlByteLoader with the specified content and loader. +func NewYamlByteLoader[Type any](content []byte, loader ConfigLoader[Type]) ConfigLoader[Type] { + return &YamlByteLoader[Type]{ + content: content, + ConfigLoader: loader, + } +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go index 9f6f06df1f..2e7e735be4 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory.go @@ -18,9 +18,13 @@ package azclient import ( + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/deploymentclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/ipgroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient" @@ -28,14 +32,18 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privateendpointclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatelinkserviceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatezoneclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipprefixclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/resourcegroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/sshpublickeyresourceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/subnetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient" @@ -43,9 +51,13 @@ import ( ) type ClientFactory interface { + GetAccountClient() accountclient.Interface GetAvailabilitySetClient() availabilitysetclient.Interface + GetBlobContainerClient() blobcontainerclient.Interface + GetBlobServicePropertiesClient() blobservicepropertiesclient.Interface GetDeploymentClient() deploymentclient.Interface GetDiskClient() diskclient.Interface + GetFileShareClient() fileshareclient.Interface GetInterfaceClient() interfaceclient.Interface GetIPGroupClient() ipgroupclient.Interface GetLoadBalancerClient() loadbalancerclient.Interface @@ -53,14 +65,18 @@ type ClientFactory interface { GetPrivateEndpointClient() privateendpointclient.Interface GetPrivateLinkServiceClient() privatelinkserviceclient.Interface GetPrivateZoneClient() privatezoneclient.Interface + GetProviderClient() providerclient.Interface GetPublicIPAddressClient() publicipaddressclient.Interface GetPublicIPPrefixClient() publicipprefixclient.Interface + GetRegistryClient() registryclient.Interface GetResourceGroupClient() resourcegroupclient.Interface GetRouteTableClient() routetableclient.Interface + GetSecretClient() secretclient.Interface GetSecurityGroupClient() securitygroupclient.Interface GetSnapshotClient() snapshotclient.Interface GetSSHPublicKeyResourceClient() sshpublickeyresourceclient.Interface GetSubnetClient() subnetclient.Interface + GetVaultClient() vaultclient.Interface GetVirtualMachineClient() virtualmachineclient.Interface GetVirtualMachineScaleSetClient() virtualmachinescalesetclient.Interface GetVirtualMachineScaleSetVMClient() virtualmachinescalesetvmclient.Interface diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go index 0eb25bad61..d3808b5446 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/factory_gen.go @@ -23,9 +23,13 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/deploymentclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/ipgroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient" @@ -34,14 +38,18 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privateendpointclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatelinkserviceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatezoneclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipprefixclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/resourcegroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/snapshotclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/sshpublickeyresourceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/subnetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient" @@ -51,9 +59,13 @@ import ( type ClientFactoryImpl struct { *ClientFactoryConfig cred azcore.TokenCredential + accountclientInterface accountclient.Interface availabilitysetclientInterface availabilitysetclient.Interface + blobcontainerclientInterface blobcontainerclient.Interface + blobservicepropertiesclientInterface blobservicepropertiesclient.Interface deploymentclientInterface deploymentclient.Interface diskclientInterface diskclient.Interface + fileshareclientInterface fileshareclient.Interface interfaceclientInterface interfaceclient.Interface ipgroupclientInterface ipgroupclient.Interface loadbalancerclientInterface loadbalancerclient.Interface @@ -61,14 +73,18 @@ type ClientFactoryImpl struct { privateendpointclientInterface privateendpointclient.Interface privatelinkserviceclientInterface privatelinkserviceclient.Interface privatezoneclientInterface privatezoneclient.Interface + providerclientInterface providerclient.Interface publicipaddressclientInterface publicipaddressclient.Interface publicipprefixclientInterface publicipprefixclient.Interface + registryclientInterface registryclient.Interface resourcegroupclientInterface resourcegroupclient.Interface routetableclientInterface routetableclient.Interface + secretclientInterface secretclient.Interface securitygroupclientInterface securitygroupclient.Interface snapshotclientInterface snapshotclient.Interface sshpublickeyresourceclientInterface sshpublickeyresourceclient.Interface subnetclientInterface subnetclient.Interface + vaultclientInterface vaultclient.Interface virtualmachineclientInterface virtualmachineclient.Interface virtualmachinescalesetclientInterface virtualmachinescalesetclient.Interface virtualmachinescalesetvmclientInterface virtualmachinescalesetvmclient.Interface @@ -86,7 +102,7 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c var options *arm.ClientOptions var err error - //initialize {availabilitysetclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient AvailabilitySet Interface availabilitySetRateLimit} + //initialize {accountclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient Account Interface } options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { return nil, err @@ -94,6 +110,17 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c var ratelimitOption *ratelimit.Config var rateLimitPolicy policy.Policy + + accountclientInterface, err := accountclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + + //initialize {availabilitysetclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient AvailabilitySet Interface availabilitySetRateLimit} + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } //add ratelimit policy ratelimitOption = config.GetRateLimitConfig("availabilitySetRateLimit") rateLimitPolicy = ratelimit.NewRateLimitPolicy(ratelimitOption) @@ -105,6 +132,28 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return nil, err } + //initialize {blobcontainerclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient Account BlobContainer Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + blobcontainerclientInterface, err := blobcontainerclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + + //initialize {blobservicepropertiesclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobservicepropertiesclient BlobServiceProperties Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + blobservicepropertiesclientInterface, err := blobservicepropertiesclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + //initialize {deploymentclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/deploymentclient Deployment Interface deploymentRateLimit} options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { @@ -137,6 +186,17 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return nil, err } + //initialize {fileshareclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient Account FileShare Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + fileshareclientInterface, err := fileshareclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + //initialize {interfaceclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient Interface Interface interfaceRateLimit} options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { @@ -249,6 +309,17 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return nil, err } + //initialize {providerclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient Provider Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + providerclientInterface, err := providerclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + //initialize {publicipaddressclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient PublicIPAddress Interface publicIPAddressRateLimit} options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { @@ -276,6 +347,17 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return nil, err } + //initialize {registryclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient Registry Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + registryclientInterface, err := registryclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + //initialize {resourcegroupclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/resourcegroupclient ResourceGroup Interface } options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { @@ -303,6 +385,17 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return nil, err } + //initialize {secretclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient Vault Secret Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + secretclientInterface, err := secretclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + //initialize {securitygroupclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient SecurityGroup Interface securityGroupRateLimit} options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { @@ -362,6 +455,17 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return nil, err } + //initialize {vaultclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient Vault Interface } + options, err = GetDefaultResourceClientOption(armConfig, config) + if err != nil { + return nil, err + } + + vaultclientInterface, err := vaultclient.New(config.SubscriptionID, cred, options) + if err != nil { + return nil, err + } + //initialize {virtualmachineclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient VirtualMachine Interface virtualMachineRateLimit} options, err = GetDefaultResourceClientOption(armConfig, config) if err != nil { @@ -418,9 +522,13 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c return &ClientFactoryImpl{ ClientFactoryConfig: config, - cred: cred, availabilitysetclientInterface: availabilitysetclientInterface, + cred: cred, accountclientInterface: accountclientInterface, + availabilitysetclientInterface: availabilitysetclientInterface, + blobcontainerclientInterface: blobcontainerclientInterface, + blobservicepropertiesclientInterface: blobservicepropertiesclientInterface, deploymentclientInterface: deploymentclientInterface, diskclientInterface: diskclientInterface, + fileshareclientInterface: fileshareclientInterface, interfaceclientInterface: interfaceclientInterface, ipgroupclientInterface: ipgroupclientInterface, loadbalancerclientInterface: loadbalancerclientInterface, @@ -428,14 +536,18 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c privateendpointclientInterface: privateendpointclientInterface, privatelinkserviceclientInterface: privatelinkserviceclientInterface, privatezoneclientInterface: privatezoneclientInterface, + providerclientInterface: providerclientInterface, publicipaddressclientInterface: publicipaddressclientInterface, publicipprefixclientInterface: publicipprefixclientInterface, + registryclientInterface: registryclientInterface, resourcegroupclientInterface: resourcegroupclientInterface, routetableclientInterface: routetableclientInterface, + secretclientInterface: secretclientInterface, securitygroupclientInterface: securitygroupclientInterface, snapshotclientInterface: snapshotclientInterface, sshpublickeyresourceclientInterface: sshpublickeyresourceclientInterface, subnetclientInterface: subnetclientInterface, + vaultclientInterface: vaultclientInterface, virtualmachineclientInterface: virtualmachineclientInterface, virtualmachinescalesetclientInterface: virtualmachinescalesetclientInterface, virtualmachinescalesetvmclientInterface: virtualmachinescalesetvmclientInterface, @@ -443,10 +555,22 @@ func NewClientFactory(config *ClientFactoryConfig, armConfig *ARMClientConfig, c }, nil } +func (factory *ClientFactoryImpl) GetAccountClient() accountclient.Interface { + return factory.accountclientInterface +} + func (factory *ClientFactoryImpl) GetAvailabilitySetClient() availabilitysetclient.Interface { return factory.availabilitysetclientInterface } +func (factory *ClientFactoryImpl) GetBlobContainerClient() blobcontainerclient.Interface { + return factory.blobcontainerclientInterface +} + +func (factory *ClientFactoryImpl) GetBlobServicePropertiesClient() blobservicepropertiesclient.Interface { + return factory.blobservicepropertiesclientInterface +} + func (factory *ClientFactoryImpl) GetDeploymentClient() deploymentclient.Interface { return factory.deploymentclientInterface } @@ -455,6 +579,10 @@ func (factory *ClientFactoryImpl) GetDiskClient() diskclient.Interface { return factory.diskclientInterface } +func (factory *ClientFactoryImpl) GetFileShareClient() fileshareclient.Interface { + return factory.fileshareclientInterface +} + func (factory *ClientFactoryImpl) GetInterfaceClient() interfaceclient.Interface { return factory.interfaceclientInterface } @@ -483,6 +611,10 @@ func (factory *ClientFactoryImpl) GetPrivateZoneClient() privatezoneclient.Inter return factory.privatezoneclientInterface } +func (factory *ClientFactoryImpl) GetProviderClient() providerclient.Interface { + return factory.providerclientInterface +} + func (factory *ClientFactoryImpl) GetPublicIPAddressClient() publicipaddressclient.Interface { return factory.publicipaddressclientInterface } @@ -491,6 +623,10 @@ func (factory *ClientFactoryImpl) GetPublicIPPrefixClient() publicipprefixclient return factory.publicipprefixclientInterface } +func (factory *ClientFactoryImpl) GetRegistryClient() registryclient.Interface { + return factory.registryclientInterface +} + func (factory *ClientFactoryImpl) GetResourceGroupClient() resourcegroupclient.Interface { return factory.resourcegroupclientInterface } @@ -499,6 +635,10 @@ func (factory *ClientFactoryImpl) GetRouteTableClient() routetableclient.Interfa return factory.routetableclientInterface } +func (factory *ClientFactoryImpl) GetSecretClient() secretclient.Interface { + return factory.secretclientInterface +} + func (factory *ClientFactoryImpl) GetSecurityGroupClient() securitygroupclient.Interface { return factory.securitygroupclientInterface } @@ -515,6 +655,10 @@ func (factory *ClientFactoryImpl) GetSubnetClient() subnetclient.Interface { return factory.subnetclientInterface } +func (factory *ClientFactoryImpl) GetVaultClient() vaultclient.Interface { + return factory.vaultclientInterface +} + func (factory *ClientFactoryImpl) GetVirtualMachineClient() virtualmachineclient.Interface { return factory.virtualmachineclientInterface } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/custom.go new file mode 100644 index 0000000000..8b8e4c3b42 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/custom.go @@ -0,0 +1,45 @@ +/* +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 fileshareclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" +) + +func (client *Client) Create(ctx context.Context, resourceGroupName string, resourceName string, parentResourceName string, resource armstorage.FileShare) (*armstorage.FileShare, error) { + resp, err := client.FileSharesClient.Create(ctx, resourceGroupName, resourceName, parentResourceName, resource, nil) + if err != nil { + return nil, err + } + return &resp.FileShare, nil +} + +func (client *Client) Update(ctx context.Context, resourceGroupName string, resourceName string, parentResourceName string, resource armstorage.FileShare) (*armstorage.FileShare, error) { + resp, err := client.FileSharesClient.Update(ctx, resourceGroupName, resourceName, parentResourceName, resource, nil) + if err != nil { + return nil, err + } + return &resp.FileShare, nil +} + +// Delete deletes a FileShare by name. +func (client *Client) Delete(ctx context.Context, resourceGroupName string, parentResourceName string, resourceName string) error { + _, err := client.FileSharesClient.Delete(ctx, resourceGroupName, parentResourceName, resourceName, nil) + return err +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/interface.go new file mode 100644 index 0000000000..e040d42ceb --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/interface.go @@ -0,0 +1,34 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package fileshareclient + +import ( + "context" + + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// +azure:client:verbs=get,resource=Account,subResource=FileShare,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage,packageAlias=armstorage,clientName=FileSharesClient,expand=false +type Interface interface { + utils.SubResourceGetFunc[armstorage.FileShare] + Create(ctx context.Context, resourceGroupName string, resourceName string, parentResourceName string, resource armstorage.FileShare) (*armstorage.FileShare, error) + Update(ctx context.Context, resourceGroupName string, resourceName string, parentResourceName string, resource armstorage.FileShare) (*armstorage.FileShare, error) + Delete(ctx context.Context, resourceGroupName string, parentResourceName string, resourceName string) error +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/zz_generated_client.go new file mode 100644 index 0000000000..df5316dc25 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/fileshareclient/zz_generated_client.go @@ -0,0 +1,55 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package fileshareclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armstorage "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armstorage.FileSharesClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armstorage.NewFileSharesClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +// Get gets the FileShare +func (client *Client) Get(ctx context.Context, resourceGroupName string, parentResourceName string, resourceName string) (result *armstorage.FileShare, rerr error) { + + resp, err := client.FileSharesClient.Get(ctx, resourceGroupName, parentResourceName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.FileShare, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/custom.go new file mode 100644 index 0000000000..7a59c4a211 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/custom.go @@ -0,0 +1,46 @@ +/* +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 interfaceclient + +import ( + "context" + + armnetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4" +) + +// List gets a list of IPGroup in the resource group. +func (client *Client) ListVirtualMachineScaleSetNetworkInterfaces(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) ([]*armnetwork.Interface, error) { + pager := client.InterfacesClient.NewListVirtualMachineScaleSetNetworkInterfacesPager(resourceGroupName, virtualMachineScaleSetName, nil) + var result []*armnetwork.Interface + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} + +func (client *Client) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string) (*armnetwork.Interface, error) { + resp, err := client.InterfacesClient.GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.Interface, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/interface.go index cd169cbf99..ee01a6fa1c 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/interface.go @@ -28,7 +28,8 @@ import ( // +azure:client:verbs=get;createorupdate;delete;list,resource=Interface,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4,packageAlias=armnetwork,clientName=InterfacesClient,expand=true,rateLimitKey=interfaceRateLimit type Interface interface { // GetVirtualMachineScaleSetNetworkInterface gets a network.Interface of VMSS VM. - GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, options *armnetwork.InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceOptions) (armnetwork.InterfacesClientGetVirtualMachineScaleSetNetworkInterfaceResponse, error) + GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string) (*armnetwork.Interface, error) + ListVirtualMachineScaleSetNetworkInterfaces(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) ([]*armnetwork.Interface, error) utils.GetWithExpandFunc[armnetwork.Interface] utils.CreateOrUpdateFunc[armnetwork.Interface] utils.DeleteFunc[armnetwork.Interface] diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/custom.go new file mode 100644 index 0000000000..8e93304079 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/custom.go @@ -0,0 +1,62 @@ +/* +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 providerclient + +import ( + "context" + "strings" + + armresources "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" +) + +func (client *Client) ListProviders(ctx context.Context) (result []*armresources.Provider, rerr error) { + pager := client.ProvidersClient.NewListPager(nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} +func (client *Client) GetProvider(ctx context.Context, resourceProviderNamespace string) (*armresources.Provider, error) { + resp, err := client.ProvidersClient.Get(ctx, resourceProviderNamespace, nil) + if err != nil { + return nil, err + } + return &resp.Provider, nil +} + +func (client *Client) GetVirtualMachineSupportedZones(ctx context.Context) (map[string][]*string, error) { + result, err := client.GetProvider(ctx, "Microsoft.Compute") + if err != nil { + return nil, err + } + regionZoneMap := make(map[string][]*string) + + for _, resourceType := range result.ResourceTypes { + if strings.EqualFold(*resourceType.ResourceType, "virtualMachines") { + for _, zoneMapping := range resourceType.ZoneMappings { + location := strings.ToLower(strings.ReplaceAll(*zoneMapping.Location, " ", "")) + regionZoneMap[location] = zoneMapping.Zones + } + + } + } + return regionZoneMap, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/interface.go new file mode 100644 index 0000000000..056c3945a1 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/interface.go @@ -0,0 +1,31 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package providerclient + +import ( + "context" + + armresources "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" +) + +// +azure:client:resource=Provider,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources,packageAlias=armresources,clientName=ProvidersClient,expand=false +type Interface interface { + ListProviders(ctx context.Context) ([]*armresources.Provider, error) + GetProvider(ctx context.Context, resourceProviderNamespace string) (*armresources.Provider, error) + GetVirtualMachineSupportedZones(ctx context.Context) (map[string][]*string, error) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/zz_generated_client.go new file mode 100644 index 0000000000..abe9d55da0 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient/zz_generated_client.go @@ -0,0 +1,42 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package providerclient + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armresources "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armresources.ProvidersClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armresources.NewProvidersClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/custom.go new file mode 100644 index 0000000000..325defc100 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/custom.go @@ -0,0 +1,41 @@ +/* +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 registryclient + +import ( + "context" + + armcontainerregistry "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +func (client *Client) Create(ctx context.Context, resourceGroupName string, resourceName string, resourceParam armcontainerregistry.Registry) (*armcontainerregistry.Registry, error) { + resp, err := utils.NewPollerWrapper(client.RegistriesClient.BeginCreate(ctx, resourceGroupName, resourceName, resourceParam, nil)).WaitforPollerResp(ctx) + if err != nil { + return nil, err + } + if resp != nil { + return &resp.Registry, nil + } + return nil, nil +} + +func (client *Client) ImportImage(ctx context.Context, resourceGroup string, resourceName string, param armcontainerregistry.ImportImageParameters) error { + _, err := utils.NewPollerWrapper(client.RegistriesClient.BeginImportImage(ctx, resourceGroup, resourceName, param, nil)).WaitforPollerResp(ctx) + return err +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/interface.go new file mode 100644 index 0000000000..9374497a0a --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/interface.go @@ -0,0 +1,35 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package registryclient + +import ( + "context" + + armcontainerregistry "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// +azure:client:verbs=get;delete;listbyrg,resource=Registry,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry,packageAlias=armcontainerregistry,clientName=RegistriesClient,expand=false +type Interface interface { + utils.GetFunc[armcontainerregistry.Registry] + Create(ctx context.Context, resourceGroupName string, resourceName string, resourceParam armcontainerregistry.Registry) (*armcontainerregistry.Registry, error) + utils.DeleteFunc[armcontainerregistry.Registry] + utils.ListFunc[armcontainerregistry.Registry] + ImportImage(ctx context.Context, resourceGroup string, resourceName string, param armcontainerregistry.ImportImageParameters) error +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/zz_generated_client.go new file mode 100644 index 0000000000..ac1a3ff27a --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/registryclient/zz_generated_client.go @@ -0,0 +1,74 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package registryclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armcontainerregistry "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armcontainerregistry.RegistriesClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armcontainerregistry.NewRegistriesClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +// Get gets the Registry +func (client *Client) Get(ctx context.Context, resourceGroupName string, resourceName string) (result *armcontainerregistry.Registry, rerr error) { + + resp, err := client.RegistriesClient.Get(ctx, resourceGroupName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.Registry, nil +} + +// Delete deletes a Registry by name. +func (client *Client) Delete(ctx context.Context, resourceGroupName string, resourceName string) error { + _, err := utils.NewPollerWrapper(client.BeginDelete(ctx, resourceGroupName, resourceName, nil)).WaitforPollerResp(ctx) + return err +} + +// List gets a list of Registry in the resource group. +func (client *Client) List(ctx context.Context, resourceGroupName string) (result []*armcontainerregistry.Registry, rerr error) { + pager := client.RegistriesClient.NewListByResourceGroupPager(resourceGroupName, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/interface.go index c99d456d50..7755a36bfa 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/interface.go @@ -23,8 +23,10 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" ) -// +azure:client:verbs=createorupdate;delete,resource=RouteTable,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4,packageAlias=armnetwork,clientName=RouteTablesClient,expand=false,rateLimitKey=routeTableRateLimit +// +azure:client:verbs=get;createorupdate;delete;list,resource=RouteTable,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4,packageAlias=armnetwork,clientName=RouteTablesClient,expand=false,rateLimitKey=routeTableRateLimit type Interface interface { utils.CreateOrUpdateFunc[armnetwork.RouteTable] utils.DeleteFunc[armnetwork.RouteTable] + utils.ListFunc[armnetwork.RouteTable] + utils.GetFunc[armnetwork.RouteTable] } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/zz_generated_client.go index f671cfb264..cd8b30f838 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/zz_generated_client.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/zz_generated_client.go @@ -43,6 +43,17 @@ func New(subscriptionID string, credential azcore.TokenCredential, options *arm. return &Client{client}, nil } +// Get gets the RouteTable +func (client *Client) Get(ctx context.Context, resourceGroupName string, resourceName string) (result *armnetwork.RouteTable, rerr error) { + + resp, err := client.RouteTablesClient.Get(ctx, resourceGroupName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.RouteTable, nil +} + // CreateOrUpdate creates or updates a RouteTable. func (client *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, resource armnetwork.RouteTable) (*armnetwork.RouteTable, error) { resp, err := utils.NewPollerWrapper(client.RouteTablesClient.BeginCreateOrUpdate(ctx, resourceGroupName, resourceName, resource, nil)).WaitforPollerResp(ctx) @@ -60,3 +71,16 @@ func (client *Client) Delete(ctx context.Context, resourceGroupName string, reso _, err := utils.NewPollerWrapper(client.BeginDelete(ctx, resourceGroupName, resourceName, nil)).WaitforPollerResp(ctx) return err } + +// List gets a list of RouteTable in the resource group. +func (client *Client) List(ctx context.Context, resourceGroupName string) (result []*armnetwork.RouteTable, rerr error) { + pager := client.RouteTablesClient.NewListPager(resourceGroupName, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/custom.go new file mode 100644 index 0000000000..83d4f7daa5 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/custom.go @@ -0,0 +1,32 @@ +/* +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 secretclient + +import ( + "context" + + armkeyvault "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault" +) + +// CreateOrUpdate creates or updates a Secret. +func (client *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, parentResourceName string, resource armkeyvault.SecretCreateOrUpdateParameters) (*armkeyvault.Secret, error) { + resp, err := client.SecretsClient.CreateOrUpdate(ctx, resourceGroupName, resourceName, parentResourceName, resource, nil) + if err != nil { + return nil, err + } + return &resp.Secret, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/interface.go new file mode 100644 index 0000000000..1138915d63 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/interface.go @@ -0,0 +1,33 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package secretclient + +import ( + "context" + + armkeyvault "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// +azure:client:verbs=get;list,resource=Vault,subResource=Secret,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault,packageAlias=armkeyvault,clientName=SecretsClient,expand=false +type Interface interface { + utils.SubResourceGetFunc[armkeyvault.Secret] + CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, parentResourceName string, resource armkeyvault.SecretCreateOrUpdateParameters) (*armkeyvault.Secret, error) + utils.SubResourceListFunc[armkeyvault.Secret] +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/zz_generated_client.go new file mode 100644 index 0000000000..4a508c715f --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/secretclient/zz_generated_client.go @@ -0,0 +1,68 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package secretclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armkeyvault "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armkeyvault.SecretsClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armkeyvault.NewSecretsClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +// Get gets the Secret +func (client *Client) Get(ctx context.Context, resourceGroupName string, parentResourceName string, resourceName string) (result *armkeyvault.Secret, rerr error) { + + resp, err := client.SecretsClient.Get(ctx, resourceGroupName, parentResourceName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.Secret, nil +} + +// List gets a list of Secret in the resource group. +func (client *Client) List(ctx context.Context, resourceGroupName string, parentResourceName string) (result []*armkeyvault.Secret, rerr error) { + pager := client.SecretsClient.NewListPager(resourceGroupName, parentResourceName, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/custom.go new file mode 100644 index 0000000000..298ec44073 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/custom.go @@ -0,0 +1,48 @@ +/* +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 vaultclient + +import ( + "context" + + armkeyvault "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// Delete deletes a Vault by name. +func (client *Client) Delete(ctx context.Context, resourceGroupName string, resourceName string) error { + _, err := client.VaultsClient.Delete(ctx, resourceGroupName, resourceName, nil) + return err +} + +// CreateOrUpdate creates or updates a Vault. +func (client *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, resource armkeyvault.VaultCreateOrUpdateParameters) (*armkeyvault.Vault, error) { + resp, err := utils.NewPollerWrapper(client.VaultsClient.BeginCreateOrUpdate(ctx, resourceGroupName, resourceName, resource, nil)).WaitforPollerResp(ctx) + if err != nil { + return nil, err + } + if resp != nil { + return &resp.Vault, nil + } + return nil, nil +} + +func (client *Client) PurgeDeleted(ctx context.Context, vaultName string, location string) error { + _, err := utils.NewPollerWrapper(client.BeginPurgeDeleted(ctx, vaultName, location, nil)).WaitforPollerResp(ctx) + return err +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/interface.go new file mode 100644 index 0000000000..50027f2128 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/interface.go @@ -0,0 +1,35 @@ +/* +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. +*/ + +// +azure:enableclientgen:=true +package vaultclient + +import ( + "context" + + armkeyvault "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +// +azure:client:verbs=get;listbyrg,resource=Vault,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault,packageAlias=armkeyvault,clientName=VaultsClient,expand=false +type Interface interface { + utils.GetFunc[armkeyvault.Vault] + CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, resource armkeyvault.VaultCreateOrUpdateParameters) (*armkeyvault.Vault, error) + utils.DeleteFunc[armkeyvault.Vault] + PurgeDeleted(ctx context.Context, vaultName string, location string) error + utils.ListFunc[armkeyvault.Vault] +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/zz_generated_client.go new file mode 100644 index 0000000000..195e5e45bf --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/vaultclient/zz_generated_client.go @@ -0,0 +1,68 @@ +// /* +// 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 client-gen. DO NOT EDIT. +package vaultclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armkeyvault "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" +) + +type Client struct { + *armkeyvault.VaultsClient +} + +func New(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (Interface, error) { + if options == nil { + options = utils.GetDefaultOption() + } + + client, err := armkeyvault.NewVaultsClient(subscriptionID, credential, options) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +// Get gets the Vault +func (client *Client) Get(ctx context.Context, resourceGroupName string, resourceName string) (result *armkeyvault.Vault, rerr error) { + + resp, err := client.VaultsClient.Get(ctx, resourceGroupName, resourceName, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.Vault, nil +} + +// List gets a list of Vault in the resource group. +func (client *Client) List(ctx context.Context, resourceGroupName string) (result []*armkeyvault.Vault, rerr error) { + pager := client.VaultsClient.NewListByResourceGroupPager(resourceGroupName, nil) + for pager.More() { + nextResult, err := pager.NextPage(ctx) + if err != nil { + return nil, err + } + result = append(result, nextResult.Value...) + } + return result, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/custom.go new file mode 100644 index 0000000000..16c9ddc0cf --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/custom.go @@ -0,0 +1,37 @@ +/* +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 virtualmachinescalesetclient + +import ( + "context" + + armcompute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" +) + +// Get gets the VirtualMachineScaleSet +func (client *Client) Get(ctx context.Context, resourceGroupName string, resourceName string, expand *armcompute.ExpandTypesForGetVMScaleSets) (result *armcompute.VirtualMachineScaleSet, rerr error) { + var ops *armcompute.VirtualMachineScaleSetsClientGetOptions + if expand != nil { + ops = &armcompute.VirtualMachineScaleSetsClientGetOptions{Expand: expand} + } + resp, err := client.VirtualMachineScaleSetsClient.Get(ctx, resourceGroupName, resourceName, ops) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.VirtualMachineScaleSet, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/interface.go index ebc97c029c..852a734702 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/interface.go @@ -18,14 +18,16 @@ limitations under the License. package virtualmachinescalesetclient import ( + "context" + armcompute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" ) -// +azure:client:verbs=get;createorupdate;delete;list,resource=VirtualMachineScaleSet,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5,packageAlias=armcompute,clientName=VirtualMachineScaleSetsClient,expand=false,rateLimitKey=virtualMachineSizesRateLimit +// +azure:client:verbs=createorupdate;delete;list,resource=VirtualMachineScaleSet,packageName=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5,packageAlias=armcompute,clientName=VirtualMachineScaleSetsClient,expand=true,rateLimitKey=virtualMachineSizesRateLimit type Interface interface { - utils.GetFunc[armcompute.VirtualMachineScaleSet] + Get(ctx context.Context, resourceGroupName string, resourceName string, expand *armcompute.ExpandTypesForGetVMScaleSets) (result *armcompute.VirtualMachineScaleSet, rerr error) utils.CreateOrUpdateFunc[armcompute.VirtualMachineScaleSet] utils.DeleteFunc[armcompute.VirtualMachineScaleSet] utils.ListFunc[armcompute.VirtualMachineScaleSet] diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/zz_generated_client.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/zz_generated_client.go index 4f0c60b600..42a0d99648 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/zz_generated_client.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/zz_generated_client.go @@ -43,17 +43,6 @@ func New(subscriptionID string, credential azcore.TokenCredential, options *arm. return &Client{client}, nil } -// Get gets the VirtualMachineScaleSet -func (client *Client) Get(ctx context.Context, resourceGroupName string, resourceName string) (result *armcompute.VirtualMachineScaleSet, rerr error) { - - resp, err := client.VirtualMachineScaleSetsClient.Get(ctx, resourceGroupName, resourceName, nil) - if err != nil { - return nil, err - } - //handle statuscode - return &resp.VirtualMachineScaleSet, nil -} - // CreateOrUpdate creates or updates a VirtualMachineScaleSet. func (client *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, resource armcompute.VirtualMachineScaleSet) (*armcompute.VirtualMachineScaleSet, error) { resp, err := utils.NewPollerWrapper(client.VirtualMachineScaleSetsClient.BeginCreateOrUpdate(ctx, resourceGroupName, resourceName, resource, nil)).WaitforPollerResp(ctx) diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/custom.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/custom.go new file mode 100644 index 0000000000..f51623940c --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/custom.go @@ -0,0 +1,32 @@ +/* +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 virtualnetworkclient + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4" +) + +func (client *Client) CheckIPAddressAvailability(ctx context.Context, resourceGroupName string, virtualNetworkName string, ipAddress string) (*armnetwork.IPAddressAvailabilityResult, error) { + resp, err := client.VirtualNetworksClient.CheckIPAddressAvailability(ctx, resourceGroupName, virtualNetworkName, ipAddress, nil) + if err != nil { + return nil, err + } + //handle statuscode + return &resp.IPAddressAvailabilityResult, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/interface.go index c9404ba4dc..f601144756 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient/interface.go @@ -18,6 +18,8 @@ limitations under the License. package virtualnetworkclient import ( + "context" + armnetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v4" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/utils" @@ -29,4 +31,5 @@ type Interface interface { utils.CreateOrUpdateFunc[armnetwork.VirtualNetwork] utils.DeleteFunc[armnetwork.VirtualNetwork] utils.ListFunc[armnetwork.VirtualNetwork] + CheckIPAddressAvailability(ctx context.Context, resourceGroupName string, virtualNetworkName string, ipAddress string) (*armnetwork.IPAddressAvailabilityResult, error) } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/deploymentclient/azure_deploymentclient.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/deploymentclient/azure_deploymentclient.go index 8a15249704..b99124d165 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/deploymentclient/azure_deploymentclient.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/deploymentclient/azure_deploymentclient.go @@ -440,7 +440,7 @@ func (c *Client) ExportTemplate(ctx context.Context, resourceGroupName string, d defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deployment.exportTemplate.request", resourceID, rerr.Error()) - return + return result, rerr } err := autorest.Respond( diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/azure_vmssclient.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/azure_vmssclient.go index e24a435a2f..dc0e45a5c0 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/azure_vmssclient.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/azure_vmssclient.go @@ -474,7 +474,7 @@ func (c *Client) DeleteInstances(ctx context.Context, resourceGroupName string, return nil } -// DeleteInstancesAsync sends the delete request to ARM client and DOEST NOT wait on the future +// 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, "") @@ -529,7 +529,7 @@ func (c *Client) DeleteInstancesAsync(ctx context.Context, resourceGroupName str return &future, nil } -// DeallocateInstancesAsync sends the deallocate request to ARM client and DOEST NOT wait on the future +// 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, "") @@ -578,7 +578,7 @@ func (c *Client) DeallocateInstancesAsync(ctx context.Context, resourceGroupName return &future, nil } -// StartInstancesAsync sends the start request to ARM client and DOEST NOT wait on the future +// 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, "") diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/interface.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/interface.go index c88e1ad068..10c9d04703 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/interface.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/interface.go @@ -56,7 +56,7 @@ type Interface interface { // 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 DOEST NOT wait on the future + // 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 @@ -65,7 +65,7 @@ type Interface interface { // 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 DOEST NOT wait on the future + // 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 diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go index c9e075d2fb..723a4f89c3 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/consts.go @@ -17,6 +17,7 @@ limitations under the License. package consts import ( + "strings" "time" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage" @@ -156,8 +157,6 @@ const ( // NonVmssUniformNodesCacheTTLDefaultInSeconds is the TTL of the non vmss uniform node cache NonVmssUniformNodesCacheTTLDefaultInSeconds = 900 - // AvailabilitySetNodesCacheTTLDefaultInSeconds is the TTL of the availabilitySet node cache - AvailabilitySetNodesCacheTTLDefaultInSeconds = 900 // VMSSCacheTTLDefaultInSeconds is the TTL of the vmss cache VMSSCacheTTLDefaultInSeconds = 600 // VMSSVirtualMachinesCacheTTLDefaultInSeconds is the TTL of the vmss vm cache @@ -203,6 +202,8 @@ const ( IPVersionDualStackString string = "DualStack" ) +var IPVersionIPv6StringLower = strings.ToLower(IPVersionIPv6String) + // LB variables for dual-stack var ( // Service.Spec.LoadBalancerIP has been deprecated and may be removed in a future release. Those two annotations are introduced as alternatives to set IPv4/IPv6 LoadBalancer IPs. @@ -281,10 +282,15 @@ const ( // ServiceAnnotationIPTagsForPublicIP specifies the iptags used when dynamically creating a public ip ServiceAnnotationIPTagsForPublicIP = "service.beta.kubernetes.io/azure-pip-ip-tags" - // ServiceAnnotationAllowedServiceTag is the annotation used on the service + // ServiceAnnotationAllowedServiceTags is the annotation used on the service // to specify a list of allowed service tags separated by comma // Refer https://docs.microsoft.com/en-us/azure/virtual-network/security-overview#service-tags for all supported service tags. - ServiceAnnotationAllowedServiceTag = "service.beta.kubernetes.io/azure-allowed-service-tags" + ServiceAnnotationAllowedServiceTags = "service.beta.kubernetes.io/azure-allowed-service-tags" + + // ServiceAnnotationAllowedIPRanges is the annotation used on the service + // to specify a list of allowed IP Ranges separated by comma. + // It is compatible with both IPv4 and IPV6 CIDR formats. + ServiceAnnotationAllowedIPRanges = "service.beta.kubernetes.io/azure-allowed-ip-ranges" // ServiceAnnotationDenyAllExceptLoadBalancerSourceRanges denies all traffic to the load balancer except those // within the service.Spec.LoadBalancerSourceRanges. Ref: https://github.com/kubernetes-sigs/cloud-provider-azure/issues/374. @@ -333,6 +339,9 @@ const ( // The list is separated by comma. It will be omitted if multi-slb is not used. ServiceAnnotationLoadBalancerConfigurations = "service.beta.kubernetes.io/azure-load-balancer-configurations" + // ServiceAnnotationDisableTCPReset is the annotation used on the service to disable TCP reset on the load balancer. + ServiceAnnotationDisableTCPReset = "service.beta.kubernetes.io/azure-load-balancer-disable-tcp-reset" + // ServiceTagKey is the service key applied for public IP tags. ServiceTagKey = "k8s-azure-service" LegacyServiceTagKey = "service" @@ -494,6 +503,9 @@ const ( // ServiceAnnotationPLSCreation determines whether a PLS needs to be created. ServiceAnnotationPLSCreation = "service.beta.kubernetes.io/azure-pls-create" + // ServiceAnnotationPLSResourceGroup determines the resource group to create the PLS in. + ServiceAnnotationPLSResourceGroup = "service.beta.kubernetes.io/azure-pls-resource-group" + // ServiceAnnotationPLSName determines name of the PLS resource to create. ServiceAnnotationPLSName = "service.beta.kubernetes.io/azure-pls-name" @@ -549,3 +561,12 @@ const ( ServiceNameLabel = "kubernetes.io/service-name" ) + +// Load Balancer health probe mode +const ( + ClusterServiceLoadBalancerHealthProbeModeServiceNodePort = "servicenodeport" + ClusterServiceLoadBalancerHealthProbeModeShared = "shared" + ClusterServiceLoadBalancerHealthProbeDefaultPort = 10256 + ClusterServiceLoadBalancerHealthProbeDefaultPath = "/healthz" + SharedProbeName = "cluster-service-shared-health-probe" +) diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/helpers.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/helpers.go index 9706b55aa9..c6636b0d20 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/helpers.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/consts/helpers.go @@ -65,6 +65,11 @@ func IsPLSEnabled(annotations map[string]string) bool { return expectAttributeInSvcAnnotationBeEqualTo(annotations, ServiceAnnotationPLSCreation, TrueAnnotationValue) } +// IsTCPResetDisabled return true if ServiceAnnotationDisableTCPReset is true +func IsTCPResetDisabled(annotations map[string]string) bool { + return expectAttributeInSvcAnnotationBeEqualTo(annotations, ServiceAnnotationDisableTCPReset, TrueAnnotationValue) +} + // Getint32ValueFromK8sSvcAnnotation get health probe configuration for port func Getint32ValueFromK8sSvcAnnotation(annotations map[string]string, key string, validators ...Int32BusinessValidator) (*int32, error) { val, err := GetAttributeValueInSvcAnnotation(annotations, key) @@ -74,7 +79,7 @@ func Getint32ValueFromK8sSvcAnnotation(annotations map[string]string, key string return nil, err } -// BuildHealthProbeAnnotationKeyForPort get health probe configuration key for port +// BuildAnnotationKeyForPort get health probe configuration key for port func BuildAnnotationKeyForPort(port int32, key PortParams) string { return fmt.Sprintf(PortAnnotationPrefixPattern, port, string(key)) } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go index a1ccec51a8..b887a6ea3c 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure.go @@ -27,12 +27,9 @@ import ( "sync" "time" - ratelimitconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" - "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" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" @@ -46,8 +43,13 @@ import ( "k8s.io/client-go/tools/record" "k8s.io/client-go/util/flowcontrol" cloudprovider "k8s.io/cloud-provider" + cloudproviderapi "k8s.io/cloud-provider/api" + cloudnodeutil "k8s.io/cloud-provider/node/helpers" + nodeutil "k8s.io/component-helpers/node/util" "k8s.io/klog/v2" + "sigs.k8s.io/yaml" + "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/blobclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/containerserviceclient" @@ -76,9 +78,9 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/zoneclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" + ratelimitconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/retry" - - "sigs.k8s.io/yaml" + "sigs.k8s.io/cloud-provider-azure/pkg/util/taints" ) var ( @@ -88,6 +90,14 @@ var ( defaultDisableOutboundSNAT = false // RouteUpdateWaitingInSeconds is 30 seconds by default. defaultRouteUpdateWaitingInSeconds = 30 + nodeOutOfServiceTaint = &v1.Taint{ + Key: v1.TaintNodeOutOfService, + Effect: v1.TaintEffectNoExecute, + } + nodeShutdownTaint = &v1.Taint{ + Key: cloudproviderapi.TaintNodeShutdown, + Effect: v1.TaintEffectNoSchedule, + } ) // Config holds the configuration parsed from the --cloud-config flag @@ -206,9 +216,6 @@ type Config struct { // NonVmssUniformNodesCacheTTLInSeconds sets the Cache TTL for NonVmssUniformNodesCacheTTLInSeconds // if not set, will use default value NonVmssUniformNodesCacheTTLInSeconds int `json:"nonVmssUniformNodesCacheTTLInSeconds,omitempty" yaml:"nonVmssUniformNodesCacheTTLInSeconds,omitempty"` - // AvailabilitySetNodesCacheTTLInSeconds sets the Cache TTL for availabilitySetNodesCache - // if not set, will use default value - AvailabilitySetNodesCacheTTLInSeconds int `json:"availabilitySetNodesCacheTTLInSeconds,omitempty" yaml:"availabilitySetNodesCacheTTLInSeconds,omitempty"` // VmssCacheTTLInSeconds sets the cache TTL for VMSS VmssCacheTTLInSeconds int `json:"vmssCacheTTLInSeconds,omitempty" yaml:"vmssCacheTTLInSeconds,omitempty"` // VmssVirtualMachinesCacheTTLInSeconds sets the cache TTL for vmssVirtualMachines @@ -269,6 +276,16 @@ type Config struct { RouteUpdateIntervalInSeconds int `json:"routeUpdateIntervalInSeconds,omitempty" yaml:"routeUpdateIntervalInSeconds,omitempty"` // LoadBalancerBackendPoolUpdateIntervalInSeconds is the interval for updating load balancer backend pool of local services. Default is 30 seconds. LoadBalancerBackendPoolUpdateIntervalInSeconds int `json:"loadBalancerBackendPoolUpdateIntervalInSeconds,omitempty" yaml:"loadBalancerBackendPoolUpdateIntervalInSeconds,omitempty"` + + // ClusterServiceLoadBalancerHealthProbeMode determines the health probe mode for cluster service load balancer. + // Supported values are `shared` and `servicenodeport`. + // `unshared`: the health probe will be created against each port of each service by watching the backend application (default). + // `shared`: all cluster services shares one HTTP probe targeting the kube-proxy on the node (/healthz:10256). + ClusterServiceLoadBalancerHealthProbeMode string `json:"clusterServiceLoadBalancerHealthProbeMode,omitempty" yaml:"clusterServiceLoadBalancerHealthProbeMode,omitempty"` + // ClusterServiceSharedLoadBalancerHealthProbePort defines the target port of the shared health probe. Default to 10256. + ClusterServiceSharedLoadBalancerHealthProbePort int32 `json:"clusterServiceSharedLoadBalancerHealthProbePort,omitempty" yaml:"clusterServiceSharedLoadBalancerHealthProbePort,omitempty"` + // ClusterServiceSharedLoadBalancerHealthProbePath defines the target path of the shared health probe. Default to `/healthz`. + ClusterServiceSharedLoadBalancerHealthProbePath string `json:"clusterServiceSharedLoadBalancerHealthProbePath,omitempty" yaml:"clusterServiceSharedLoadBalancerHealthProbePath,omitempty"` } // MultipleStandardLoadBalancerConfiguration stores the properties regarding multiple standard load balancers. @@ -321,12 +338,6 @@ type MultipleStandardLoadBalancerConfigurationStatus struct { ActiveNodes sets.Set[string] `json:"activeNodes" yaml:"activeNodes"` } -type InitSecretConfig struct { - SecretName string `json:"secretName,omitempty" yaml:"secretName,omitempty"` - SecretNamespace string `json:"secretNamespace,omitempty" yaml:"secretNamespace,omitempty"` - CloudConfigKey string `json:"cloudConfigKey,omitempty" yaml:"cloudConfigKey,omitempty"` -} - // HasExtendedLocation returns true if extendedlocation prop are specified. func (config *Config) HasExtendedLocation() bool { return config.ExtendedLocationName != "" && config.ExtendedLocationType != "" @@ -344,7 +355,6 @@ var ( // Cloud holds the config and clients type Cloud struct { Config - InitSecretConfig Environment azure.Environment RoutesClient routeclient.Interface @@ -421,7 +431,7 @@ type Cloud struct { // key: [resourceGroupName] // Value: sync.Map of [pipName]*PublicIPAddress pipCache azcache.Resource - // use LB frontEndIpConfiguration ID as the key and search for PLS attached to the frontEnd + // use [resourceGroupName*LBFrontEndIpConfigurationID] as the key and search for PLS attached to the frontEnd plsCache azcache.Resource // a timed cache storing storage account properties to avoid querying storage account frequently storageAccountCache azcache.Resource @@ -432,7 +442,6 @@ type Cloud struct { serviceReconcileLock sync.Mutex *ManagedDiskController - *controllerCommon // multipleStandardLoadBalancerConfigurationsSynced make sure the `reconcileMultipleStandardLoadBalancerConfigurations` // runs only once every time the cloud provide restarts. @@ -446,11 +455,23 @@ type Cloud struct { } // NewCloud returns a Cloud with initialized clients -func NewCloud(ctx context.Context, configReader io.Reader, callFromCCM bool) (cloudprovider.Interface, error) { - az, err := NewCloudWithoutFeatureGates(ctx, configReader, callFromCCM) +func NewCloud(ctx context.Context, config *Config, callFromCCM bool) (cloudprovider.Interface, error) { + az := &Cloud{ + nodeNames: sets.New[string](), + nodeZones: map[string]sets.Set[string]{}, + nodeResourceGroups: map[string]string{}, + unmanagedNodes: sets.New[string](), + routeCIDRs: map[string]string{}, + excludeLoadBalancerNodes: sets.New[string](), + nodePrivateIPs: map[string]sets.Set[string]{}, + nodePrivateIPToNodeNameMap: map[string]string{}, + } + + err := az.InitializeCloudFromConfig(ctx, config, false, callFromCCM) if err != nil { return nil, err } + az.ipv6DualStackEnabled = true return az, nil @@ -462,6 +483,7 @@ func NewCloudFromConfigFile(ctx context.Context, configFilePath string, calFromC err error ) + var configValue *Config if configFilePath != "" { var config *os.File config, err = os.Open(configFilePath) @@ -471,12 +493,12 @@ func NewCloudFromConfigFile(ctx context.Context, configFilePath string, calFromC } defer config.Close() - cloud, err = NewCloud(ctx, config, calFromCCM) - } else { - // Pass explicit nil so plugins can actually check for nil. See - // "Why is my nil error value not equal to nil?" in golang.org/doc/faq. - cloud, err = NewCloud(ctx, nil, false) + configValue, err = ParseConfig(config) + if err != nil { + klog.Fatalf("Failed to parse Azure cloud provider config: %v", err) + } } + cloud, err = NewCloud(ctx, configValue, calFromCCM && configFilePath != "") if err != nil { return nil, fmt.Errorf("could not init cloud provider azure: %w", err) @@ -488,73 +510,23 @@ func NewCloudFromConfigFile(ctx context.Context, configFilePath string, calFromC return cloud, nil } -func (az *Cloud) configSecretMetadata(secretName, secretNamespace, cloudConfigKey string) { - if secretName == "" { - secretName = consts.DefaultCloudProviderConfigSecName - } - if secretNamespace == "" { - secretNamespace = consts.DefaultCloudProviderConfigSecNamespace - } - if cloudConfigKey == "" { - cloudConfigKey = consts.DefaultCloudProviderConfigSecKey - } - - az.InitSecretConfig = InitSecretConfig{ - SecretName: secretName, - SecretNamespace: secretNamespace, - CloudConfigKey: cloudConfigKey, - } -} - func NewCloudFromSecret(ctx context.Context, clientBuilder cloudprovider.ControllerClientBuilder, secretName, secretNamespace, cloudConfigKey string) (cloudprovider.Interface, error) { - az := &Cloud{ - nodeNames: sets.New[string](), - nodeZones: map[string]sets.Set[string]{}, - nodeResourceGroups: map[string]string{}, - unmanagedNodes: sets.New[string](), - routeCIDRs: map[string]string{}, - excludeLoadBalancerNodes: sets.New[string](), - nodePrivateIPs: map[string]sets.Set[string]{}, - nodePrivateIPToNodeNameMap: map[string]string{}, - } - - az.configSecretMetadata(secretName, secretNamespace, cloudConfigKey) - - az.Initialize(clientBuilder, wait.NeverStop) - - err := az.InitializeCloudFromSecret(ctx) + config, err := configloader.Load[Config](ctx, &configloader.K8sSecretLoaderConfig{ + K8sSecretConfig: configloader.K8sSecretConfig{ + SecretName: secretName, + SecretNamespace: secretNamespace, + CloudConfigKey: cloudConfigKey, + }, + KubeClient: clientBuilder.ClientOrDie("cloud-provider-azure"), + }, nil) if err != nil { - return nil, fmt.Errorf("NewCloudFromSecret: failed to initialize cloud from secret %s/%s: %w", az.SecretNamespace, az.SecretName, err) + return nil, fmt.Errorf("NewCloudFromSecret: failed to get config from secret %s/%s: %w", secretNamespace, secretName, err) } - - az.ipv6DualStackEnabled = true - - return az, nil -} - -// NewCloudWithoutFeatureGates returns a Cloud without trying to wire the feature gates. This is used by the unit tests -// that don't load the actual features being used in the cluster. -func NewCloudWithoutFeatureGates(ctx context.Context, configReader io.Reader, callFromCCM bool) (*Cloud, error) { - config, err := ParseConfig(configReader) + az, err := NewCloud(ctx, config, true) if err != nil { - return nil, err - } - - az := &Cloud{ - nodeNames: sets.New[string](), - nodeZones: map[string]sets.Set[string]{}, - nodeResourceGroups: map[string]string{}, - unmanagedNodes: sets.New[string](), - routeCIDRs: map[string]string{}, - excludeLoadBalancerNodes: sets.New[string](), - nodePrivateIPs: map[string]sets.Set[string]{}, - nodePrivateIPToNodeNameMap: map[string]string{}, - } - - err = az.InitializeCloudFromConfig(ctx, config, false, callFromCCM) - if err != nil { - return nil, err + return nil, fmt.Errorf("NewCloudFromSecret: failed to initialize cloud from secret %s/%s: %w", secretNamespace, secretName, err) } + az.Initialize(clientBuilder, wait.NeverStop) return az, nil } @@ -618,29 +590,28 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, } } - env, err := ratelimitconfig.ParseAzureEnvironment(config.Cloud, config.ResourceManagerEndpoint, config.IdentitySystem) - if err != nil { - return err + if config.ClusterServiceLoadBalancerHealthProbeMode == "" { + config.ClusterServiceLoadBalancerHealthProbeMode = consts.ClusterServiceLoadBalancerHealthProbeModeServiceNodePort + } else { + supportedClusterServiceLoadBalancerHealthProbeModes := sets.New( + strings.ToLower(consts.ClusterServiceLoadBalancerHealthProbeModeServiceNodePort), + strings.ToLower(consts.ClusterServiceLoadBalancerHealthProbeModeShared), + ) + if !supportedClusterServiceLoadBalancerHealthProbeModes.Has(strings.ToLower(config.ClusterServiceLoadBalancerHealthProbeMode)) { + return fmt.Errorf("clusterServiceLoadBalancerHealthProbeMode %s is not supported, supported values are %v", config.ClusterServiceLoadBalancerHealthProbeMode, supportedClusterServiceLoadBalancerHealthProbeModes.UnsortedList()) + } } - - servicePrincipalToken, err := ratelimitconfig.GetServicePrincipalToken(&config.AzureAuthConfig, env, env.ServiceManagementEndpoint) - if errors.Is(err, ratelimitconfig.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) - return err + if strings.EqualFold(config.ClusterServiceLoadBalancerHealthProbeMode, consts.ClusterServiceLoadBalancerHealthProbeModeShared) { + if config.ClusterServiceSharedLoadBalancerHealthProbePort == 0 { + config.ClusterServiceSharedLoadBalancerHealthProbePort = consts.ClusterServiceLoadBalancerHealthProbeDefaultPort } - - // 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. - if !config.UseInstanceMetadata && config.CloudConfigType == cloudConfigTypeFile { - return fmt.Errorf("useInstanceMetadata must be enabled without Azure credentials") + if config.ClusterServiceSharedLoadBalancerHealthProbePath == "" { + config.ClusterServiceSharedLoadBalancerHealthProbePath = consts.ClusterServiceLoadBalancerHealthProbeDefaultPath } + } - klog.V(2).Infof("Azure cloud provider is starting without credentials") - } else if err != nil { + env, err := ratelimitconfig.ParseAzureEnvironment(config.Cloud, config.ResourceManagerEndpoint, config.IdentitySystem) + if err != nil { return err } @@ -662,18 +633,6 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, 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 - } - - // If uses network resources in different AAD Tenant, then prepare corresponding Service Principal Token for VM/VMSS client and network resources client - err = az.configureMultiTenantClients(servicePrincipalToken) - if err != nil { - return err - } - if az.MaximumLoadBalancerRuleCount == 0 { az.MaximumLoadBalancerRuleCount = consts.MaximumLoadBalancerRuleCount } @@ -706,15 +665,65 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config, return err } } + servicePrincipalToken, err := ratelimitconfig.GetServicePrincipalToken(&config.AzureAuthConfig, env, env.ServiceManagementEndpoint) + if errors.Is(err, ratelimitconfig.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) + return err + } + + // 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. + if !config.UseInstanceMetadata && config.CloudConfigType == cloudConfigTypeFile { + return fmt.Errorf("useInstanceMetadata must be enabled without Azure credentials") + } + + 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 + } + + // 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) + if err != nil { + return err + } + az.configAzureClients(servicePrincipalToken, multiTenantServicePrincipalToken, networkResourceServicePrincipalToken) err = az.initCaches() if err != nil { return err } - if err := initDiskControllers(az); err != nil { + if err := InitDiskControllers(az); err != nil { return err } + // Common controller contains the function + // needed by both blob disk and managed disk controllers + qps := float32(ratelimitconfig.DefaultAtachDetachDiskQPS) + bucket := ratelimitconfig.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) + + common := &controllerCommon{ + cloud: az, + lockMap: newLockMap(), + diskOpRateLimiter: flowcontrol.NewTokenBucketRateLimiter(qps, bucket), + AttachDetachInitialDelayInMs: defaultAttachDetachInitialDelayInMs, + } + + az.ManagedDiskController = &ManagedDiskController{common} // updating routes and syncing zones only in CCM if callFromCCM { @@ -862,23 +871,21 @@ func (az *Cloud) setLBDefaults(config *Config) error { return nil } -func (az *Cloud) configureMultiTenantClients(servicePrincipalToken *adal.ServicePrincipalToken) error { +func (az *Cloud) getAuthTokenInMultiTenantEnv(servicePrincipalToken *adal.ServicePrincipalToken) (*adal.MultiTenantServicePrincipalToken, *adal.ServicePrincipalToken, error) { var err error var multiTenantServicePrincipalToken *adal.MultiTenantServicePrincipalToken var networkResourceServicePrincipalToken *adal.ServicePrincipalToken if az.Config.UsesNetworkResourceInDifferentTenant() { multiTenantServicePrincipalToken, err = ratelimitconfig.GetMultiTenantServicePrincipalToken(&az.Config.AzureAuthConfig, &az.Environment) if err != nil { - return err + return nil, nil, err } networkResourceServicePrincipalToken, err = ratelimitconfig.GetNetworkResourceServicePrincipalToken(&az.Config.AzureAuthConfig, &az.Environment) if err != nil { - return err + return nil, nil, err } } - - az.configAzureClients(servicePrincipalToken, multiTenantServicePrincipalToken, networkResourceServicePrincipalToken) - return nil + return multiTenantServicePrincipalToken, networkResourceServicePrincipalToken, nil } func (az *Cloud) setCloudProviderBackoffDefaults(config *Config) wait.Backoff { @@ -1141,7 +1148,7 @@ func (az *Cloud) ProviderName() string { return consts.CloudProviderName } -func initDiskControllers(az *Cloud) error { +func InitDiskControllers(az *Cloud) error { // Common controller contains the function // needed by both blob disk and managed disk controllers @@ -1160,8 +1167,7 @@ func initDiskControllers(az *Cloud) error { AttachDetachInitialDelayInMs: defaultAttachDetachInitialDelayInMs, } - az.ManagedDiskController = &ManagedDiskController{common: common} - az.controllerCommon = common + az.ManagedDiskController = &ManagedDiskController{common} return nil } @@ -1174,11 +1180,13 @@ func (az *Cloud) SetInformers(informerFactory informers.SharedInformerFactory) { AddFunc: func(obj interface{}) { node := obj.(*v1.Node) az.updateNodeCaches(nil, node) + az.updateNodeTaint(node) }, UpdateFunc: func(prev, obj interface{}) { prevNode := prev.(*v1.Node) newNode := obj.(*v1.Node) az.updateNodeCaches(prevNode, newNode) + az.updateNodeTaint(newNode) }, DeleteFunc: func(obj interface{}) { node, isNode := obj.(*v1.Node) @@ -1244,18 +1252,19 @@ func (az *Cloud) updateNodeCaches(prevNode, newNode *v1.Node) { az.unmanagedNodes.Delete(prevNode.ObjectMeta.Name) } - // if the node is being deleted from the cluster, exclude it from load balancers - if newNode == nil { - az.excludeLoadBalancerNodes.Insert(prevNode.ObjectMeta.Name) - az.nodesWithCorrectLoadBalancerByPrimaryVMSet.Delete(strings.ToLower(prevNode.ObjectMeta.Name)) - } - // Remove from nodePrivateIPs cache. for _, address := range getNodePrivateIPAddresses(prevNode) { - klog.V(4).Infof("removing IP address %s of the node %s", address, prevNode.Name) + klog.V(6).Infof("removing IP address %s of the node %s", address, prevNode.Name) az.nodePrivateIPs[prevNode.Name].Delete(address) delete(az.nodePrivateIPToNodeNameMap, address) } + + // if the node is being deleted from the cluster, exclude it from load balancers + if newNode == nil { + az.excludeLoadBalancerNodes.Insert(prevNode.ObjectMeta.Name) + az.nodesWithCorrectLoadBalancerByPrimaryVMSet.Delete(strings.ToLower(prevNode.ObjectMeta.Name)) + delete(az.nodePrivateIPs, strings.ToLower(prevNode.Name)) + } } if newNode != nil { @@ -1304,20 +1313,49 @@ func (az *Cloud) updateNodeCaches(prevNode, newNode *v1.Node) { // Add to nodePrivateIPs cache for _, address := range getNodePrivateIPAddresses(newNode) { - if az.nodePrivateIPs[newNode.Name] == nil { - az.nodePrivateIPs[newNode.Name] = sets.New[string]() + if az.nodePrivateIPs[strings.ToLower(newNode.Name)] == nil { + az.nodePrivateIPs[strings.ToLower(newNode.Name)] = sets.New[string]() } if az.nodePrivateIPToNodeNameMap == nil { az.nodePrivateIPToNodeNameMap = make(map[string]string) } klog.V(6).Infof("adding IP address %s of the node %s", address, newNode.Name) - az.nodePrivateIPs[newNode.Name].Insert(address) + az.nodePrivateIPs[strings.ToLower(newNode.Name)].Insert(address) az.nodePrivateIPToNodeNameMap[address] = newNode.Name } } } +// updateNodeTaint updates node out-of-service taint +func (az *Cloud) updateNodeTaint(node *v1.Node) { + if node == nil { + klog.Warningf("node is nil, skip updating node out-of-service taint (should not happen)") + return + } + if az.KubeClient == nil { + klog.Warningf("az.KubeClient is nil, skip updating node out-of-service taint") + return + } + + if isNodeReady(node) { + if err := cloudnodeutil.RemoveTaintOffNode(az.KubeClient, node.Name, node, nodeOutOfServiceTaint); err != nil { + klog.Errorf("failed to remove taint %s from the node %s", v1.TaintNodeOutOfService, node.Name) + } + } else { + // node shutdown taint is added when cloud provider determines instance is shutdown + if !taints.TaintExists(node.Spec.Taints, nodeOutOfServiceTaint) && + taints.TaintExists(node.Spec.Taints, nodeShutdownTaint) { + klog.V(2).Infof("adding %s taint to node %s", v1.TaintNodeOutOfService, node.Name) + if err := cloudnodeutil.AddOrUpdateTaintOnNode(az.KubeClient, node.Name, nodeOutOfServiceTaint); err != nil { + klog.Errorf("failed to add taint %s to the node %s", v1.TaintNodeOutOfService, node.Name) + } + } else { + klog.V(2).Infof("node %s is not ready but either shutdown taint is missing or out-of-service taint is already added, skip adding node out-of-service taint", node.Name) + } + } +} + // GetActiveZones returns all the zones in which k8s nodes are currently running. func (az *Cloud) GetActiveZones() (sets.Set[string], error) { if az.nodeInformerSynced == nil { @@ -1452,3 +1490,13 @@ func (az *Cloud) getActiveNodesByLoadBalancerName(lbName string) sets.Set[string return sets.New[string]() } + +func isNodeReady(node *v1.Node) bool { + if node == nil { + return false + } + if _, c := nodeutil.GetNodeCondition(&node.Status, v1.NodeReady); c != nil { + return c.Status == v1.ConditionTrue + } + return false +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_config.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_config.go index 6711c5f651..ccfac71846 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_config.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_config.go @@ -16,16 +16,6 @@ limitations under the License. package provider -import ( - "context" - "fmt" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/klog/v2" - - "sigs.k8s.io/yaml" -) - // The config type for Azure cloud provider secret. Supported values are: // * file : The values are read from local cloud-config file. // * secret : The values from secret would override all configures from local cloud-config file. @@ -37,54 +27,3 @@ const ( cloudConfigTypeSecret cloudConfigType = "secret" cloudConfigTypeMerge cloudConfigType = "merge" ) - -// InitializeCloudFromSecret initializes Azure cloud provider from Kubernetes secret. -func (az *Cloud) InitializeCloudFromSecret(ctx context.Context) error { - config, err := az.GetConfigFromSecret() - if err != nil { - klog.Errorf("Failed to get cloud-config from secret: %v", err) - return fmt.Errorf("InitializeCloudFromSecret: failed to get cloud config from secret %s/%s: %w", az.SecretNamespace, az.SecretName, err) - } - - if config == nil { - // Skip re-initialization if the config is not override. - return nil - } - - if err := az.InitializeCloudFromConfig(ctx, config, true, true); err != nil { - klog.Errorf("Failed to initialize Azure cloud provider: %v", err) - return fmt.Errorf("InitializeCloudFromSecret: failed to initialize Azure cloud provider: %w", err) - } - - return nil -} - -func (az *Cloud) GetConfigFromSecret() (*Config, error) { - // Read config from file and no override, return nil. - if az.Config.CloudConfigType == cloudConfigTypeFile { - return nil, nil - } - - secret, err := az.KubeClient.CoreV1().Secrets(az.SecretNamespace).Get(context.TODO(), az.SecretName, metav1.GetOptions{}) - if err != nil { - return nil, fmt.Errorf("failed to get secret %s/%s: %w", az.SecretNamespace, az.SecretName, err) - } - - cloudConfigData, ok := secret.Data[az.CloudConfigKey] - if !ok { - return nil, fmt.Errorf("cloud-config is not set in the secret (%s/%s)", az.SecretNamespace, az.SecretName) - } - - config := Config{} - if az.Config.CloudConfigType == "" || az.Config.CloudConfigType == cloudConfigTypeMerge { - // Merge cloud config, set default value to existing config. - config = az.Config - } - - err = yaml.Unmarshal(cloudConfigData, &config) - if err != nil { - return nil, fmt.Errorf("failed to parse Azure cloud-config: %w", err) - } - - return &config, nil -} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go index 3a494ecdf9..4ce4d9c47d 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_standard.go @@ -265,7 +265,7 @@ func (as *availabilitySet) UpdateVMAsync(ctx context.Context, nodeName types.Nod } func (as *availabilitySet) updateCache(nodeName string, vm *compute.VirtualMachine) { - if as.common.DisableUpdateCache { + if as.ManagedDiskController.DisableUpdateCache { return } as.cloud.vmCache.Update(nodeName, vm) diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go index e3ad7a9b7e..17c914dd48 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_controller_vmssflex.go @@ -264,7 +264,7 @@ func (fs *FlexScaleSet) UpdateVMAsync(ctx context.Context, nodeName types.NodeNa } func (fs *FlexScaleSet) updateCache(nodeName string, vm *compute.VirtualMachine) error { - if fs.common.DisableUpdateCache { + if fs.ManagedDiskController.DisableUpdateCache { return nil } if vm == nil { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go index 58d764473f..cf58e172fd 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_fakes.go @@ -128,7 +128,7 @@ func GetTestCloud(ctrl *gomock.Controller) (az *Cloud) { az.LoadBalancerBackendPool = NewMockBackendPool(ctrl) az.storageAccountCache, _ = az.newStorageAccountCache() - _ = initDiskControllers(az) + _ = InitDiskControllers(az) az.regionZonesMap = map[string][]string{az.Location: {"1", "2", "3"}} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances.go index f14fe57d61..656a2b8735 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_instances.go @@ -37,6 +37,7 @@ const ( vmPowerStateStopped = "stopped" vmPowerStateDeallocated = "deallocated" vmPowerStateDeallocating = "deallocating" + vmPowerStateUnknown = "unknown" // nodeNameEnvironmentName is the environment variable name for getting node name. // It is only used for out-of-tree cloud provider. diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go index 21d9b404ab..8301937b3c 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer.go @@ -41,13 +41,13 @@ import ( cloudprovider "k8s.io/cloud-provider" servicehelpers "k8s.io/cloud-provider/service/helpers" "k8s.io/klog/v2" - utilnet "k8s.io/utils/net" "k8s.io/utils/pointer" "k8s.io/utils/strings/slices" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" + "sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer" "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) @@ -167,6 +167,12 @@ func (az *Cloud) reconcileService(ctx context.Context, clusterName string, servi key := strings.ToLower(serviceName) if az.useMultipleStandardLoadBalancers() && isLocalService(service) { az.localServiceNameToServiceInfoMap.Store(key, newServiceInfo(getServiceIPFamily(service), lbName)) + // There are chances that the endpointslice changes after EnsureHostsInPool, so + // need to check endpointslice for a second time. + if err := az.checkAndApplyLocalServiceBackendPoolUpdates(*lb, service); err != nil { + klog.Errorf("failed to checkAndApplyLocalServiceBackendPoolUpdates: %v", err) + return nil, err + } } else { az.localServiceNameToServiceInfoMap.Delete(key) } @@ -1635,25 +1641,22 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service, // reconcile the load balancer's backend pool configuration. if wantLb { - preConfig, changed, shouldRefreshLB, err := az.LoadBalancerBackendPool.ReconcileBackendPools(clusterName, service, lb) + var ( + preConfig, backendPoolsUpdated bool + err error + ) + preConfig, backendPoolsUpdated, lb, err = az.LoadBalancerBackendPool.ReconcileBackendPools(clusterName, service, lb) if err != nil { return lb, err } - if changed { + if backendPoolsUpdated { dirtyLb = true } isBackendPoolPreConfigured = preConfig // If the LB is changed, refresh it to avoid etag mismatch error // later when create or update the LB. - if shouldRefreshLB { - klog.V(4).Infof("reconcileLoadBalancer for service(%s): refreshing load balancer %s", serviceName, lbName) - lb, _, err = az.getAzureLoadBalancer(lbName, azcache.CacheReadTypeForceRefresh) - if err != nil { - return lb, fmt.Errorf("reconcileLoadBalancer for service (%s): failed to get load balancer %s: %w", serviceName, lbName, err) - } - addOrUpdateLBInList(existingLBs, lb) - } + addOrUpdateLBInList(existingLBs, lb) } // reconcile the load balancer's frontend IP configurations. @@ -1801,18 +1804,9 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service, if az.useMultipleStandardLoadBalancers() { lbToReconcile = *existingLBs } - for _, lb := range lbToReconcile { - lbName := pointer.StringDeref(lb.Name, "") - if lb.LoadBalancerPropertiesFormat != nil && lb.LoadBalancerPropertiesFormat.BackendAddressPools != nil { - for _, backendPool := range *lb.LoadBalancerPropertiesFormat.BackendAddressPools { - isIPv6 := isBackendPoolIPv6(pointer.StringDeref(backendPool.Name, "")) - if strings.EqualFold(pointer.StringDeref(backendPool.Name, ""), az.getBackendPoolNameForService(service, clusterName, isIPv6)) { - if err := az.LoadBalancerBackendPool.EnsureHostsInPool(service, nodes, lbBackendPoolIDs[isIPv6], vmSetName, clusterName, lbName, backendPool); err != nil { - return nil, err - } - } - } - } + lb, err = az.reconcileBackendPoolHosts(lb, lbToReconcile, service, nodes, clusterName, vmSetName, lbBackendPoolIDs) + if err != nil { + return nil, err } } @@ -1824,6 +1818,44 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service, return lb, nil } +func (az *Cloud) reconcileBackendPoolHosts( + currentLB *network.LoadBalancer, + lbs []network.LoadBalancer, + service *v1.Service, + nodes []*v1.Node, + clusterName, vmSetName string, + lbBackendPoolIDs map[bool]string, +) (*network.LoadBalancer, error) { + var res *network.LoadBalancer + res = currentLB + for _, lb := range lbs { + lb := lb + lbName := pointer.StringDeref(lb.Name, "") + if lb.LoadBalancerPropertiesFormat != nil && lb.LoadBalancerPropertiesFormat.BackendAddressPools != nil { + for i, backendPool := range *lb.LoadBalancerPropertiesFormat.BackendAddressPools { + isIPv6 := isBackendPoolIPv6(pointer.StringDeref(backendPool.Name, "")) + if strings.EqualFold(pointer.StringDeref(backendPool.Name, ""), az.getBackendPoolNameForService(service, clusterName, isIPv6)) { + if err := az.LoadBalancerBackendPool.EnsureHostsInPool( + service, + nodes, + lbBackendPoolIDs[isIPv6], + vmSetName, + clusterName, + lbName, + (*lb.LoadBalancerPropertiesFormat.BackendAddressPools)[i], + ); err != nil { + return nil, err + } + } + } + } + if strings.EqualFold(lbName, *currentLB.Name) { + 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 { @@ -2542,6 +2574,7 @@ func (az *Cloud) getExpectedLBRules( // 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 nodeEndpointHealthprobeAdded bool if servicehelpers.NeedsHealthCheck(service) && !(consts.IsPLSEnabled(service.Annotations) && consts.IsPLSProxyProtocolEnabled(service.Annotations)) { podPresencePath, podPresencePort := servicehelpers.GetServiceHealthCheckPathPort(service) lbRuleName := az.getLoadBalancerRuleName(service, v1.ProtocolTCP, podPresencePort, isIPv6) @@ -2559,7 +2592,13 @@ func (az *Cloud) getExpectedLBRules( ProbeThreshold: numberOfProbes, }, } - expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) + } + + var useSharedProbe bool + if az.useSharedLoadBalancerHealthProbeMode() && + !strings.EqualFold(string(service.Spec.ExternalTrafficPolicy), string(v1.ServiceExternalTrafficPolicyLocal)) { + nodeEndpointHealthprobe = az.buildClusterServiceSharedProbe() + useSharedProbe = true } // In HA mode, lb forward traffic of all port to backend @@ -2579,7 +2618,7 @@ func (az *Cloud) getExpectedLBRules( if nodeEndpointHealthprobe == nil { // use user customized health probe rule if any for _, port := range service.Spec.Ports { - portprobe, err := az.buildHealthProbeRulesForPort(service, port, lbRuleName) + portprobe, err := az.buildHealthProbeRulesForPort(service, port, lbRuleName, nil, false) if err != nil { klog.V(2).ErrorS(err, "error occurred when buildHealthProbeRulesForPort", "service", service.Name, "namespace", service.Namespace, "rule-name", lbRuleName, "port", port.Port) @@ -2597,6 +2636,7 @@ func (az *Cloud) getExpectedLBRules( props.Probe = &network.SubResource{ ID: pointer.String(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), } + expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) } expectedRules = append(expectedRules, network.LoadBalancingRule{ @@ -2640,23 +2680,25 @@ func (az *Cloud) getExpectedLBRules( "rule-name", lbRuleName, "port", port.Port) } if !isNoHealthProbeRule { - if nodeEndpointHealthprobe == nil { - portprobe, err := az.buildHealthProbeRulesForPort(service, port, lbRuleName) - if err != nil { - klog.V(2).ErrorS(err, "error occurred when buildHealthProbeRulesForPort", "service", service.Name, "namespace", service.Namespace, - "rule-name", lbRuleName, "port", port.Port) - return expectedProbes, expectedRules, err - } - if portprobe != nil { - props.Probe = &network.SubResource{ - ID: pointer.String(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), - } - expectedProbes = append(expectedProbes, *portprobe) + portprobe, err := az.buildHealthProbeRulesForPort(service, port, lbRuleName, nodeEndpointHealthprobe, useSharedProbe) + if err != nil { + klog.V(2).ErrorS(err, "error occurred when buildHealthProbeRulesForPort", "service", service.Name, "namespace", service.Namespace, + "rule-name", lbRuleName, "port", port.Port) + return expectedProbes, expectedRules, err + } + if portprobe != nil { + props.Probe = &network.SubResource{ + ID: pointer.String(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), } - } else { + expectedProbes = append(expectedProbes, *portprobe) + } else if nodeEndpointHealthprobe != nil { props.Probe = &network.SubResource{ ID: pointer.String(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), } + if !nodeEndpointHealthprobeAdded { + expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) + nodeEndpointHealthprobeAdded = true + } } } if consts.IsK8sServiceDisableLoadBalancerFloatingIP(service) { @@ -2717,7 +2759,7 @@ func (az *Cloud) getExpectedLoadBalancingRulePropertiesForPort( IdleTimeoutInMinutes: lbIdleTimeout, } if strings.EqualFold(string(transportProto), string(network.TransportProtocolTCP)) && az.useStandardLoadBalancer() { - props.EnableTCPReset = pointer.Bool(true) + props.EnableTCPReset = pointer.Bool(!consts.IsTCPResetDisabled(service.Annotations)) } // Azure ILB does not support secondary IPs as floating IPs on the LB. Therefore, floating IP needs to be turned @@ -2738,7 +2780,8 @@ func (az *Cloud) getExpectedHAModeLoadBalancingRuleProperties( if err != nil { return nil, fmt.Errorf("error generate lb rule for ha mod loadbalancer. err: %w", err) } - props.EnableTCPReset = pointer.Bool(true) + props.EnableTCPReset = pointer.Bool(!consts.IsTCPResetDisabled(service.Annotations)) + return props, nil } @@ -2812,36 +2855,50 @@ func (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service, } } - sourceRanges, err := servicehelpers.GetLoadBalancerSourceRanges(service) + accessControl, err := loadbalancer.NewAccessControl(service) if err != nil { + klog.ErrorS(err, "Failed to parse access control configuration for service", "service", service.Name) return nil, err } - serviceTags := getServiceTags(service) - if len(serviceTags) != 0 { - delete(sourceRanges, consts.DefaultLoadBalancerSourceRanges) - } - sourceAddressPrefixes := map[bool][]string{} - if (sourceRanges == nil || servicehelpers.IsAllowAll(sourceRanges)) && len(serviceTags) == 0 { - if !requiresInternalLoadBalancer(service) || len(service.Spec.LoadBalancerSourceRanges) > 0 { - sourceAddressPrefixes[false] = []string{"Internet"} - sourceAddressPrefixes[true] = []string{"Internet"} - } - } else { - for _, ip := range sourceRanges { - if ip == nil { - continue - } - isIPv6 := net.ParseIP(ip.IP.String()).To4() == nil - sourceAddressPrefixes[isIPv6] = append(sourceAddressPrefixes[isIPv6], ip.String()) + var ( + sourceRanges = accessControl.SourceRanges() + allowedServiceTags = accessControl.AllowedServiceTags() + allowedIPRanges = accessControl.AllowedIPRanges() + sourceAddressPrefixes = map[bool][]string{ + false: accessControl.IPV4Sources(), + true: accessControl.IPV6Sources(), } - sourceAddressPrefixes[false] = append(sourceAddressPrefixes[false], serviceTags...) - sourceAddressPrefixes[true] = append(sourceAddressPrefixes[true], serviceTags...) + ) + + if len(sourceRanges) != 0 && len(allowedIPRanges) != 0 { + // Block the service and return error if both of spec.loadBalancerSourceRanges and annotation are specified + klog.Errorf("Service %s is using both of spec.loadBalancerSourceRanges and annotation %s.", service.Name, consts.ServiceAnnotationAllowedIPRanges) + return nil, fmt.Errorf( + "both of spec.loadBalancerSourceRanges and annotation %s are specified for service %s, which is not allowed", + consts.ServiceAnnotationAllowedIPRanges, service.Name, + ) + } + if len(sourceRanges) != 0 && len(allowedServiceTags) != 0 { + // Suggesting to use aks custom annotation instead of spec.loadBalancerSourceRanges + klog.Warningf( + "Service %s is using both of spec.loadBalancerSourceRanges and annotation %s.", + service.Name, consts.ServiceAnnotationAllowedServiceTags, + ) + az.Event(service, v1.EventTypeWarning, "ConflictConfiguration", fmt.Sprintf( + "Please use annotation %s instead of spec.loadBalancerSourceRanges while using %s annotation at the same time.", + consts.ServiceAnnotationAllowedIPRanges, consts.ServiceAnnotationAllowedServiceTags, + )) } - expectedSecurityRules := []network.SecurityRule{} + var expectedSecurityRules []network.SecurityRule handleSecurityRules := func(isIPv6 bool) error { - expectedSecurityRulesSingleStack, err := az.getExpectedSecurityRules(wantLb, ports, sourceAddressPrefixes[isIPv6], service, destinationIPAddresses[isIPv6], sourceRanges, backendIPAddresses[isIPv6], disableFloatingIP, isIPv6) + expectedSecurityRulesSingleStack, err := az.getExpectedSecurityRules( + wantLb, ports, + sourceAddressPrefixes[isIPv6], service, + destinationIPAddresses[isIPv6], sourceRanges, + backendIPAddresses[isIPv6], disableFloatingIP, isIPv6, + ) expectedSecurityRules = append(expectedSecurityRules, expectedSecurityRulesSingleStack...) return err } @@ -3025,7 +3082,16 @@ func (az *Cloud) reconcileSecurityRules(sg network.SecurityGroup, return dirtySg, updatedRules, nil } -func (az *Cloud) getExpectedSecurityRules(wantLb bool, ports []v1.ServicePort, sourceAddressPrefixes []string, service *v1.Service, destinationIPAddresses []string, sourceRanges utilnet.IPNetSet, backendIPAddresses []string, disableFloatingIP, isIPv6 bool) ([]network.SecurityRule, error) { +func (az *Cloud) getExpectedSecurityRules( + wantLb bool, + ports []v1.ServicePort, + sourceAddressPrefixes []string, + service *v1.Service, + destinationIPAddresses []string, + sourceRanges []netip.Prefix, + backendIPAddresses []string, + disableFloatingIP, isIPv6 bool, +) ([]network.SecurityRule, error) { expectedSecurityRules := []network.SecurityRule{} if wantLb { @@ -3068,7 +3134,7 @@ func (az *Cloud) getExpectedSecurityRules(wantLb bool, ports []v1.ServicePort, s } shouldAddDenyRule := false - if len(sourceRanges) > 0 && !servicehelpers.IsAllowAll(sourceRanges) { + if len(sourceRanges) > 0 && !loadbalancer.IsCIDRsAllowAll(sourceRanges) { if v, ok := service.Annotations[consts.ServiceAnnotationDenyAllExceptLoadBalancerSourceRanges]; ok && strings.EqualFold(v, consts.TrueAnnotationValue) { shouldAddDenyRule = true } @@ -3827,7 +3893,7 @@ func getServiceTags(service *v1.Service) []string { return nil } - if serviceTags, found := service.Annotations[consts.ServiceAnnotationAllowedServiceTag]; found { + if serviceTags, found := service.Annotations[consts.ServiceAnnotationAllowedServiceTags]; found { result := []string{} tags := strings.Split(strings.TrimSpace(serviceTags), ",") for _, tag := range tags { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go index 28d75bdb04..d1db1e3826 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_backendpool.go @@ -52,7 +52,7 @@ type BackendPool interface { // 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(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, bool, error) + ReconcileBackendPools(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) // GetBackendPrivateIPs returns the private IPs of LoadBalancer's backend pool GetBackendPrivateIPs(clusterName string, service *v1.Service, lb *network.LoadBalancer) ([]string, []string) @@ -157,14 +157,18 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(sl return slb, nil } -func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, bool, error) { +func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( + clusterName string, + service *v1.Service, + lb *network.LoadBalancer, +) (bool, bool, *network.LoadBalancer, error) { var newBackendPools []network.BackendAddressPool var err error if lb.BackendAddressPools != nil { newBackendPools = *lb.BackendAddressPools } - var changed, shouldRefreshLB, isOperationSucceeded, isMigration bool + var backendPoolsCreated, backendPoolsUpdated, isOperationSucceeded, isMigration bool foundBackendPools := map[bool]bool{} lbName := *lb.Name @@ -201,11 +205,11 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, bp.VirtualNetwork = nil if err := bc.CreateOrUpdateLBBackendPool(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, false, fmt.Errorf("bc.ReconcileBackendPools for service (%s): failed to cleanup IP based backend pool %s: %w", serviceName, lbBackendPoolNames[isIPv6], err) + 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 - shouldRefreshLB = true + backendPoolsUpdated = true } } @@ -219,7 +223,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, klog.V(2).Infof("bc.ReconcileBackendPools for service (%s): vm not found for ipConfID %s", serviceName, ipConfID) bipConfigNotFound = append(bipConfigNotFound, ipConf) } else { - return false, false, false, err + return false, false, nil, err } } @@ -230,7 +234,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, shouldExcludeLoadBalancer, err := bc.ShouldNodeExcludedFromLoadBalancer(nodeName) if err != nil { klog.Errorf("bc.ReconcileBackendPools: ShouldNodeExcludedFromLoadBalancer(%s) failed with error: %v", nodeName, err) - return false, false, false, err + return false, false, nil, err } 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) @@ -257,17 +261,18 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, // decouple the backendPool from the node updated, err := bc.VMSet.EnsureBackendPoolDeleted(service, lbBackendPoolIDsSlice, vmSetName, &backendpoolToBeDeleted, false) if err != nil { - return false, false, false, err + return false, false, nil, err } if updated { - shouldRefreshLB = true + backendPoolsUpdated = true } } - if shouldRefreshLB { + if backendPoolsUpdated { + klog.V(4).Infof("bc.ReconcileBackendPools for service(%s): refreshing load balancer %s", serviceName, lbName) lb, _, err = bc.getAzureLoadBalancer(lbName, cache.CacheReadTypeForceRefresh) if err != nil { - return false, false, false, fmt.Errorf("bc.ReconcileBackendPools for service (%s): failed to get loadbalancer %s: %w", serviceName, lbName, err) + return false, false, nil, fmt.Errorf("bc.ReconcileBackendPools for service (%s): failed to get loadbalancer %s: %w", serviceName, lbName, err) } } @@ -278,7 +283,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, isBackendPoolPreConfigured = newBackendPool(lb, isBackendPoolPreConfigured, bc.PreConfiguredBackendPoolLoadBalancerTypes, serviceName, lbBackendPoolNames[ipFamily == v1.IPv6Protocol]) - changed = true + backendPoolsCreated = true } if isMigration { @@ -288,7 +293,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools(clusterName string, } isOperationSucceeded = true - return isBackendPoolPreConfigured, changed, false, err + return isBackendPoolPreConfigured, backendPoolsCreated, lb, err } func getBackendIPConfigurationsToBeDeleted( @@ -352,7 +357,7 @@ func (bc *backendPoolTypeNodeIPConfig) GetBackendPrivateIPs(clusterName string, klog.Errorf("bc.GetBackendPrivateIPs for service (%s): GetNodeNameByIPConfigurationID failed with error: %v", serviceName, err) continue } - privateIPsSet, ok := bc.nodePrivateIPs[nodeName] + privateIPsSet, ok := bc.nodePrivateIPs[strings.ToLower(nodeName)] if !ok { klog.Warningf("bc.GetBackendPrivateIPs for service (%s): failed to get private IPs of node %s", serviceName, nodeName) continue @@ -561,13 +566,13 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(slb *net return slb, nil } -func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, bool, error) { +func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { var newBackendPools []network.BackendAddressPool if lb.BackendAddressPools != nil { newBackendPools = *lb.BackendAddressPools } - var changed, shouldRefreshLB, isOperationSucceeded, isMigration, updated bool + var backendPoolsUpdated, shouldRefreshLB, isOperationSucceeded, isMigration, updated bool foundBackendPools := map[bool]bool{} lbName := *lb.Name serviceName := getServiceName(service) @@ -626,7 +631,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi name, err := getLBNameFromBackendPoolID(id) if err != nil { klog.Errorf("bi.ReconcileBackendPools for service (%s): failed to get LB name from backend pool ID: %s", serviceName, err.Error()) - return false, false, false, err + return false, false, nil, err } backendPoolNames = append(backendPoolNames, name) } @@ -634,7 +639,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi if err := bi.MigrateToIPBasedBackendPoolAndWaitForCompletion(lbName, backendPoolNames, nicsCountMap); err != nil { backendPoolNamesStr := strings.Join(backendPoolNames, ",") klog.Errorf("Failed to migrate to IP based backend pool for lb %s, backend pool %s: %s", lbName, backendPoolNamesStr, err.Error()) - return false, false, false, err + return false, false, nil, err } } @@ -651,14 +656,14 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi shouldRefreshLB, err = bi.VMSet.EnsureBackendPoolDeleted(service, lbBackendPoolIDsSlice, vmSetName, lb.BackendAddressPools, true) if err != nil { klog.Errorf("bi.ReconcileBackendPools for service (%s): failed to EnsureBackendPoolDeleted: %s", serviceName, err.Error()) - return false, false, false, err + return false, false, nil, err } for _, i := range bpIdxes { bp := newBackendPools[i] var nodeIPAddressesToBeDeleted []string for nodeName := range bi.excludeLoadBalancerNodes { - for ip := range bi.nodePrivateIPs[nodeName] { + for ip := range bi.nodePrivateIPs[strings.ToLower(nodeName)] { klog.V(2).Infof("bi.ReconcileBackendPools for service (%s): found unwanted node private IP %s, decouple it from the LB %s", serviceName, ip, lbName) nodeIPAddressesToBeDeleted = append(nodeIPAddressesToBeDeleted, ip) } @@ -696,7 +701,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi if updated { (*lb.BackendAddressPools)[i] = bp if err := bi.CreateOrUpdateLBBackendPool(lbName, bp); err != nil { - return false, false, false, fmt.Errorf("bi.ReconcileBackendPools for service (%s): lb backendpool - failed to update backend pool %s for load balancer %s: %w", serviceName, pointer.StringDeref(bp.Name, ""), lbName, err) + 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, pointer.StringDeref(bp.Name, ""), lbName, err) } shouldRefreshLB = true } @@ -704,6 +709,13 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi } shouldRefreshLB = shouldRefreshLB || isMigration + if shouldRefreshLB { + klog.V(4).Infof("bi.ReconcileBackendPools for service(%s): refreshing load balancer %s", serviceName, lbName) + lb, _, err = bi.getAzureLoadBalancer(lbName, cache.CacheReadTypeForceRefresh) + if err != nil { + return false, false, nil, fmt.Errorf("bi.ReconcileBackendPools for service (%s): failed to get loadbalancer %s: %w", serviceName, lbName, err) + } + } for _, ipFamily := range service.Spec.IPFamilies { if foundBackendPools[ipFamily == v1.IPv6Protocol] { @@ -712,7 +724,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi isBackendPoolPreConfigured = newBackendPool(lb, isBackendPoolPreConfigured, bi.PreConfiguredBackendPoolLoadBalancerTypes, serviceName, lbBackendPoolNames[ipFamily == v1.IPv6Protocol]) - changed = true + backendPoolsUpdated = true } if isMigration { @@ -722,7 +734,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(clusterName string, servi } isOperationSucceeded = true - return isBackendPoolPreConfigured, changed, shouldRefreshLB, nil + return isBackendPoolPreConfigured, backendPoolsUpdated, lb, nil } func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(clusterName string, service *v1.Service, lb *network.LoadBalancer) ([]string, []string) { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_healthprobe.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_healthprobe.go index 8664f907a7..4b0f0c8968 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_healthprobe.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_healthprobe.go @@ -22,16 +22,37 @@ import ( "strings" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + v1 "k8s.io/api/core/v1" + "k8s.io/klog/v2" "k8s.io/utils/pointer" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) +func (az *Cloud) buildClusterServiceSharedProbe() *network.Probe { + return &network.Probe{ + Name: pointer.String(consts.SharedProbeName), + ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Protocol: network.ProbeProtocolHTTP, + Port: pointer.Int32(az.ClusterServiceSharedLoadBalancerHealthProbePort), + RequestPath: pointer.String(az.ClusterServiceSharedLoadBalancerHealthProbePath), + IntervalInSeconds: pointer.Int32(consts.HealthProbeDefaultProbeInterval), + ProbeThreshold: pointer.Int32(consts.HealthProbeDefaultNumOfProbe), + }, + } +} + // buildHealthProbeRulesForPort // for following sku: basic loadbalancer vs standard load balancer // for following protocols: TCP HTTP HTTPS(SLB only) -func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port v1.ServicePort, lbrule string) (*network.Probe, error) { +// 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) { + if useSharedProbe { + klog.V(4).Infof("skip creating health probe for port %s because the shared probe is used", port.Port) + return nil, nil + } + if port.Protocol == v1.ProtocolUDP || port.Protocol == v1.ProtocolSCTP { return nil, nil } @@ -43,57 +64,7 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port // order - Specific Override // port_ annotation // global annotation - - // Select Protocol - // - var protocol *string - - // 1. Look up port-specific override - protocol, err = consts.GetHealthProbeConfigOfPortFromK8sSvcAnnotation(serviceManifest.Annotations, port.Port, consts.HealthProbeParamsProtocol) - if err != nil { - return nil, fmt.Errorf("failed to parse annotation %s: %w", consts.BuildHealthProbeAnnotationKeyForPort(port.Port, consts.HealthProbeParamsProtocol), err) - } - - // 2. If not specified, look up from AppProtocol - // Note - this order is to remain compatible with previous versions - if protocol == nil { - protocol = port.AppProtocol - } - - // 3. If protocol is still nil, check the global annotation - if protocol == nil { - protocol, err = consts.GetAttributeValueInSvcAnnotation(serviceManifest.Annotations, consts.ServiceAnnotationLoadBalancerHealthProbeProtocol) - if err != nil { - return nil, fmt.Errorf("failed to parse annotation %s: %w", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol, err) - } - } - - // 4. Finally, if protocol is still nil, default to TCP - if protocol == nil { - protocol = pointer.String(string(network.ProtocolTCP)) - } - - *protocol = strings.TrimSpace(*protocol) - switch { - case strings.EqualFold(*protocol, string(network.ProtocolTCP)): - properties.Protocol = network.ProbeProtocolTCP - case strings.EqualFold(*protocol, string(network.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 - } else { - properties.Protocol = network.ProbeProtocolHTTPS - } - case strings.EqualFold(*protocol, string(network.ProtocolHTTP)): - properties.Protocol = network.ProbeProtocolHTTP - default: - //For backward compatibility,when unsupported protocol is used, fall back to tcp protocol in basic lb mode instead - properties.Protocol = network.ProbeProtocolTCP - } - // Lookup or Override Health Probe Port - properties.Port = &port.NodePort probePort, err := consts.GetHealthProbeConfigOfPortFromK8sSvcAnnotation(serviceManifest.Annotations, port.Port, consts.HealthProbeParamsPort, func(s *string) error { if s == nil { @@ -148,6 +119,57 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port properties.Port = pointer.Int32(int32(port)) } } + } else if healthCheckNodePortProbe != nil { + return nil, nil + } else { + properties.Port = &port.NodePort + } + // Select Protocol + // + var protocol *string + + // 1. Look up port-specific override + protocol, err = consts.GetHealthProbeConfigOfPortFromK8sSvcAnnotation(serviceManifest.Annotations, port.Port, consts.HealthProbeParamsProtocol) + if err != nil { + return nil, fmt.Errorf("failed to parse annotation %s: %w", consts.BuildHealthProbeAnnotationKeyForPort(port.Port, consts.HealthProbeParamsProtocol), err) + } + + // 2. If not specified, look up from AppProtocol + // Note - this order is to remain compatible with previous versions + if protocol == nil { + protocol = port.AppProtocol + } + + // 3. If protocol is still nil, check the global annotation + if protocol == nil { + protocol, err = consts.GetAttributeValueInSvcAnnotation(serviceManifest.Annotations, consts.ServiceAnnotationLoadBalancerHealthProbeProtocol) + if err != nil { + return nil, fmt.Errorf("failed to parse annotation %s: %w", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol, err) + } + } + + // 4. Finally, if protocol is still nil, default to TCP + if protocol == nil { + protocol = pointer.String(string(network.ProtocolTCP)) + } + + *protocol = strings.TrimSpace(*protocol) + switch { + case strings.EqualFold(*protocol, string(network.ProtocolTCP)): + properties.Protocol = network.ProbeProtocolTCP + case strings.EqualFold(*protocol, string(network.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 + } else { + properties.Protocol = network.ProbeProtocolHTTPS + } + case strings.EqualFold(*protocol, string(network.ProtocolHTTP)): + properties.Protocol = network.ProbeProtocolHTTP + default: + //For backward compatibility,when unsupported protocol is used, fall back to tcp protocol in basic lb mode instead + properties.Protocol = network.ProbeProtocolTCP } // Select request path diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go index d18d6521a7..f92c95c5d1 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_loadbalancer_repo.go @@ -387,3 +387,12 @@ func isBackendPoolOnSameLB(newBackendPoolID string, existingBackendPools []strin return true, "", nil } + +func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool { + if !strings.EqualFold(string(service.Spec.ExternalTrafficPolicy), string(v1.ServiceExternalTrafficPolicyTypeLocal)) && + rule == consts.SharedProbeName { + return true + } + prefix := az.getRulePrefix(service) + return strings.HasPrefix(strings.ToUpper(rule), strings.ToUpper(prefix)) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go index 66ff100ed6..25ff0e8162 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_local_services.go @@ -33,6 +33,7 @@ import ( "k8s.io/client-go/informers" "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" + utilnet "k8s.io/utils/net" "k8s.io/utils/pointer" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -286,7 +287,6 @@ func (az *Cloud) getLocalServiceInfo(serviceName string) (*serviceInfo, bool) { // setUpEndpointSlicesInformer creates an informer for EndpointSlices of local services. // It watches the update events and send backend pool update operations to the batch updater. -// TODO (niqi): the update of endpointslice may be slower than tue update of endpoint pods. Need to fix this. func (az *Cloud) setUpEndpointSlicesInformer(informerFactory informers.SharedInformerFactory) { endpointSlicesInformer := informerFactory.Discovery().V1().EndpointSlices().Informer() _, _ = endpointSlicesInformer.AddEventHandler( @@ -311,7 +311,7 @@ func (az *Cloud) setUpEndpointSlicesInformer(informerFactory informers.SharedInf key := strings.ToLower(fmt.Sprintf("%s/%s", newES.Namespace, svcName)) si, found := az.getLocalServiceInfo(key) if !found { - klog.V(4).Infof("EndpointSlice %s/%s belongs to service %s, but the service is not a local service, skip updating load balancer backend pool", key, newES.Namespace, newES.Name) + klog.V(4).Infof("EndpointSlice %s/%s belongs to service %s, but the service is not a local service, or has not finished the initial reconciliation loop. Skip updating load balancer backend pool", newES.Namespace, newES.Name, key) return } lbName, ipFamily := si.lbName, si.ipFamily @@ -328,18 +328,13 @@ func (az *Cloud) setUpEndpointSlicesInformer(informerFactory informers.SharedInf } } for _, previousNodeName := range previousNodeNames { - nodeIPsSet := az.nodePrivateIPs[previousNodeName] + nodeIPsSet := az.nodePrivateIPs[strings.ToLower(previousNodeName)] previousIPs = append(previousIPs, setToStrings(nodeIPsSet)...) } for _, currentNodeName := range currentNodeNames { - nodeIPsSet := az.nodePrivateIPs[currentNodeName] + nodeIPsSet := az.nodePrivateIPs[strings.ToLower(currentNodeName)] currentIPs = append(currentIPs, setToStrings(nodeIPsSet)...) } - ipsToBeDeleted := compareNodeIPs(previousIPs, currentIPs) - if len(ipsToBeDeleted) == 0 && len(previousIPs) == len(currentIPs) { - klog.V(4).Infof("No IP change detected for EndpointSlice %s/%s, skip updating load balancer backend pool", newES.Namespace, newES.Name) - return - } if az.backendPoolUpdater != nil { var bpNames []string @@ -353,14 +348,11 @@ func (az *Cloud) setUpEndpointSlicesInformer(informerFactory informers.SharedInf default: bpNames = append(bpNames, bpNameIPv4, bpNameIPv6) } + currentIPsInBackendPools := make(map[string][]string) for _, bpName := range bpNames { - if len(ipsToBeDeleted) > 0 { - az.backendPoolUpdater.addOperation(getRemoveIPsFromBackendPoolOperation(key, lbName, bpName, ipsToBeDeleted)) - } - if len(currentIPs) > 0 { - az.backendPoolUpdater.addOperation(getAddIPsToBackendPoolOperation(key, lbName, bpName, currentIPs)) - } + currentIPsInBackendPools[bpName] = previousIPs } + az.applyIPChangesAmongLocalServiceBackendPoolsByIPFamily(lbName, key, currentIPsInBackendPools, currentIPs) } }, DeleteFunc: func(obj interface{}) { @@ -408,7 +400,7 @@ func compareNodeIPs(previousIPs, currentIPs []string) []string { func getLocalServiceBackendPoolName(serviceName string, ipv6 bool) string { serviceName = strings.ToLower(strings.Replace(serviceName, "/", "-", -1)) if ipv6 { - return fmt.Sprintf("%s-ipv6", serviceName) + return fmt.Sprintf("%s-%s", serviceName, consts.IPVersionIPv6StringLower) } return serviceName } @@ -471,12 +463,16 @@ func newServiceInfo(ipFamily, lbName string) *serviceInfo { // getLocalServiceEndpointsNodeNames gets the node names that host all endpoints of the local service. func (az *Cloud) getLocalServiceEndpointsNodeNames(service *v1.Service) (sets.Set[string], error) { - var ep *discovery_v1.EndpointSlice + var ( + ep *discovery_v1.EndpointSlice + foundInCache bool + ) az.endpointSlicesCache.Range(func(key, value interface{}) bool { endpointSlice := value.(*discovery_v1.EndpointSlice) if strings.EqualFold(getServiceNameOfEndpointSlice(endpointSlice), service.Name) && strings.EqualFold(endpointSlice.Namespace, service.Namespace) { ep = endpointSlice + foundInCache = true return false } return true @@ -499,6 +495,9 @@ func (az *Cloud) getLocalServiceEndpointsNodeNames(service *v1.Service) (sets.Se if ep == nil { return nil, fmt.Errorf("failed to find EndpointSlice for service %s/%s", service.Namespace, service.Name) } + if !foundInCache { + az.endpointSlicesCache.Store(strings.ToLower(fmt.Sprintf("%s/%s", ep.Namespace, ep.Name)), ep) + } var nodeNames []string for _, endpoint := range ep.Endpoints { @@ -544,3 +543,84 @@ func (az *Cloud) cleanupLocalServiceBackendPool( } return lbs, nil } + +// 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 { + serviceName := getServiceName(service) + endpointsNodeNames, err := az.getLocalServiceEndpointsNodeNames(service) + if err != nil { + return err + } + var expectedIPs []string + for nodeName := range endpointsNodeNames { + ips := az.nodePrivateIPs[strings.ToLower(nodeName)] + for ip := range ips { + expectedIPs = append(expectedIPs, ip) + } + } + currentIPsInBackendPools := make(map[string][]string) + for _, bp := range *lb.BackendAddressPools { + bpName := pointer.StringDeref(bp.Name, "") + if localServiceOwnsBackendPool(serviceName, bpName) { + var currentIPs []string + for _, address := range *bp.LoadBalancerBackendAddresses { + currentIPs = append(currentIPs, *address.IPAddress) + } + currentIPsInBackendPools[bpName] = currentIPs + } + } + az.applyIPChangesAmongLocalServiceBackendPoolsByIPFamily(*lb.Name, serviceName, currentIPsInBackendPools, expectedIPs) + + return nil +} + +// applyIPChangesAmongLocalServiceBackendPoolsByIPFamily reconciles IPs by IP family +// amone the backend pools of a local service. +func (az *Cloud) applyIPChangesAmongLocalServiceBackendPoolsByIPFamily( + lbName, serviceName string, + currentIPsInBackendPools map[string][]string, + expectedIPs []string, +) { + currentIPsInBackendPoolsIPv4 := make(map[string][]string) + currentIPsInBackendPoolsIPv6 := make(map[string][]string) + for bpName, ips := range currentIPsInBackendPools { + if managedResourceHasIPv6Suffix(bpName) { + currentIPsInBackendPoolsIPv6[bpName] = ips + } else { + currentIPsInBackendPoolsIPv4[bpName] = ips + } + } + + var ipv4, ipv6 []string + for _, ip := range expectedIPs { + if utilnet.IsIPv6String(ip) { + ipv6 = append(ipv6, ip) + } else { + ipv4 = append(ipv4, ip) + } + } + az.reconcileIPsInLocalServiceBackendPoolsAsync(lbName, serviceName, currentIPsInBackendPoolsIPv6, ipv6) + az.reconcileIPsInLocalServiceBackendPoolsAsync(lbName, serviceName, currentIPsInBackendPoolsIPv4, ipv4) +} + +// reconcileIPsInLocalServiceBackendPoolsAsync reconciles IPs in the backend pools of a local service. +func (az *Cloud) reconcileIPsInLocalServiceBackendPoolsAsync( + lbName, serviceName string, + currentIPsInBackendPools map[string][]string, + expectedIPs []string, +) { + for bpName, currentIPs := range currentIPsInBackendPools { + ipsToBeDeleted := compareNodeIPs(currentIPs, expectedIPs) + if len(ipsToBeDeleted) == 0 && len(currentIPs) == len(expectedIPs) { + klog.V(4).Infof("No IP change detected for service %s, skip updating load balancer backend pool", serviceName) + return + } + if len(ipsToBeDeleted) > 0 { + az.backendPoolUpdater.addOperation(getRemoveIPsFromBackendPoolOperation(serviceName, lbName, bpName, ipsToBeDeleted)) + } + if len(expectedIPs) > 0 { + az.backendPoolUpdater.addOperation(getAddIPsToBackendPoolOperation(serviceName, lbName, bpName, expectedIPs)) + } + } +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go index a0b8af849d..7121207ec3 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_managedDiskController.go @@ -39,7 +39,7 @@ import ( // ManagedDiskController : managed disk controller struct type ManagedDiskController struct { - common *controllerCommon + *controllerCommon } // ManagedDiskOptions specifies the options of managed disks. @@ -99,7 +99,7 @@ func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options * var createZones []string if len(options.AvailabilityZone) > 0 { - requestedZone := c.common.cloud.GetZoneID(options.AvailabilityZone) + requestedZone := c.cloud.GetZoneID(options.AvailabilityZone) if requestedZone != "" { createZones = append(createZones, requestedZone) } @@ -121,14 +121,14 @@ func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options * diskSizeGB := int32(options.SizeGB) diskSku := options.StorageAccountType - rg := c.common.cloud.ResourceGroup + rg := c.cloud.ResourceGroup if options.ResourceGroup != "" { rg = options.ResourceGroup } - if options.SubscriptionID != "" && !strings.EqualFold(options.SubscriptionID, c.common.cloud.SubscriptionID) && options.ResourceGroup == "" { + if options.SubscriptionID != "" && !strings.EqualFold(options.SubscriptionID, c.cloud.SubscriptionID) && options.ResourceGroup == "" { return "", fmt.Errorf("resourceGroup must be specified when subscriptionID(%s) is not empty", options.SubscriptionID) } - subsID := c.common.cloud.SubscriptionID + subsID := c.cloud.SubscriptionID if options.SubscriptionID != "" { subsID = options.SubscriptionID } @@ -229,7 +229,7 @@ func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options * diskProperties.MaxShares = &options.MaxShares } - location := c.common.cloud.Location + location := c.cloud.Location if options.Location != "" { location = options.Location } @@ -242,10 +242,10 @@ func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options * DiskProperties: &diskProperties, } - if c.common.cloud.HasExtendedLocation() { + if c.cloud.HasExtendedLocation() { model.ExtendedLocation = &compute.ExtendedLocation{ - Name: pointer.String(c.common.cloud.ExtendedLocationName), - Type: compute.ExtendedLocationTypes(c.common.cloud.ExtendedLocationType), + Name: pointer.String(c.cloud.ExtendedLocationName), + Type: compute.ExtendedLocationTypes(c.cloud.ExtendedLocationType), } } @@ -253,7 +253,7 @@ func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options * model.Zones = &createZones } - if rerr := c.common.cloud.DisksClient.CreateOrUpdate(ctx, subsID, rg, options.DiskName, model); rerr != nil { + if rerr := c.cloud.DisksClient.CreateOrUpdate(ctx, subsID, rg, options.DiskName, model); rerr != nil { return "", rerr.Error() } @@ -296,12 +296,12 @@ func (c *ManagedDiskController) DeleteManagedDisk(ctx context.Context, diskURI s return err } - if state, ok := c.common.diskStateMap.Load(strings.ToLower(diskURI)); ok { + if state, ok := c.diskStateMap.Load(strings.ToLower(diskURI)); ok { return fmt.Errorf("failed to delete disk(%s) since it's in %s state", diskURI, state.(string)) } diskName := path.Base(diskURI) - disk, rerr := c.common.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) + disk, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) if rerr != nil { if rerr.HTTPStatusCode == http.StatusNotFound { klog.V(2).Infof("azureDisk - disk(%s) is already deleted", diskURI) @@ -316,7 +316,7 @@ func (c *ManagedDiskController) DeleteManagedDisk(ctx context.Context, diskURI s return fmt.Errorf("disk(%s) already attached to node(%s), could not be deleted", diskURI, *disk.ManagedBy) } - if rerr := c.common.cloud.DisksClient.Delete(ctx, subsID, resourceGroup, diskName); rerr != nil { + if rerr := c.cloud.DisksClient.Delete(ctx, subsID, resourceGroup, diskName); rerr != nil { return rerr.Error() } // We don't need poll here, k8s will immediately stop referencing the disk @@ -329,7 +329,7 @@ func (c *ManagedDiskController) DeleteManagedDisk(ctx context.Context, diskURI s // GetDisk return: disk provisionState, diskID, error func (c *ManagedDiskController) GetDisk(ctx context.Context, subsID, resourceGroup, diskName string) (string, string, error) { - result, rerr := c.common.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) + result, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) if rerr != nil { return "", "", rerr.Error() } @@ -348,7 +348,7 @@ func (c *ManagedDiskController) ResizeDisk(ctx context.Context, diskURI string, return oldSize, err } - result, rerr := c.common.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) + result, rerr := c.cloud.DisksClient.Get(ctx, subsID, resourceGroup, diskName) if rerr != nil { return oldSize, rerr.Error() } @@ -381,7 +381,7 @@ func (c *ManagedDiskController) ResizeDisk(ctx context.Context, diskURI string, }, } - if rerr := c.common.cloud.DisksClient.Update(ctx, subsID, resourceGroup, diskName, diskParameter); rerr != nil { + if rerr := c.cloud.DisksClient.Update(ctx, subsID, resourceGroup, diskName, diskParameter); rerr != nil { return oldSize, rerr.Error() } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_loadbalancer_backendpool.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_loadbalancer_backendpool.go index 9d1911995d..1c81fb761d 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_loadbalancer_backendpool.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_loadbalancer_backendpool.go @@ -92,12 +92,12 @@ func (mr *MockBackendPoolMockRecorder) GetBackendPrivateIPs(clusterName, service } // ReconcileBackendPools mocks base method. -func (m *MockBackendPool) ReconcileBackendPools(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, bool, error) { +func (m *MockBackendPool) ReconcileBackendPools(clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReconcileBackendPools", clusterName, service, lb) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(bool) - ret2, _ := ret[2].(bool) + ret2, _ := ret[2].(*network.LoadBalancer) ret3, _ := ret[3].(error) return ret0, ret1, ret2, ret3 } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice.go index fc65530ab1..80f28045b9 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice.go @@ -86,7 +86,7 @@ func (az *Cloud) reconcilePrivateLinkService( } // Secondly, check if there is a private link service already created - existingPLS, err := az.getPrivateLinkService(fipConfigID, azcache.CacheReadTypeDefault) + existingPLS, err := az.getPrivateLinkService(az.getPLSResourceGroup(service), fipConfigID, azcache.CacheReadTypeDefault) if err != nil { klog.Errorf("reconcilePrivateLinkService for service(%s): getPrivateLinkService(%s) failed: %v", serviceName, pointer.StringDeref(fipConfigID, ""), err) return err @@ -153,14 +153,14 @@ func (az *Cloud) reconcilePrivateLinkService( return err } existingPLS.Etag = pointer.String("") - err = az.CreateOrUpdatePLS(service, existingPLS) + err = az.CreateOrUpdatePLS(service, az.getPLSResourceGroup(service), existingPLS) if err != nil { klog.Errorf("reconcilePrivateLinkService for service(%s) abort backoff: pls(%s) - updating: %s", serviceName, plsName, err.Error()) return err } } } else if !wantPLS { - existingPLS, err := az.getPrivateLinkService(fipConfigID, azcache.CacheReadTypeDefault) + existingPLS, err := az.getPrivateLinkService(az.getPLSResourceGroup(service), fipConfigID, azcache.CacheReadTypeDefault) if err != nil { klog.Errorf("reconcilePrivateLinkService for service(%s): getPrivateLinkService(%s) failed: %v", serviceName, pointer.StringDeref(fipConfigID, ""), err) return err @@ -181,6 +181,17 @@ func (az *Cloud) reconcilePrivateLinkService( return nil } +func (az *Cloud) getPLSResourceGroup(service *v1.Service) string { + if resourceGroup, found := service.Annotations[consts.ServiceAnnotationPLSResourceGroup]; found { + resourceGroupName := strings.TrimSpace(resourceGroup) + if len(resourceGroupName) > 0 { + return resourceGroupName + } + } + + return az.PrivateLinkServiceResourceGroup +} + func (az *Cloud) disablePLSNetworkPolicy(service *v1.Service) error { serviceName := getServiceName(service) subnetName := getPLSSubnetName(service) @@ -218,14 +229,14 @@ func (az *Cloud) safeDeletePLS(pls *network.PrivateLinkService, service *v1.Serv if peConns != nil { for _, peConn := range *peConns { klog.V(2).Infof("deletePLS: deleting PEConnection %s", pointer.StringDeref(peConn.Name, "")) - rerr := az.DeletePEConn(service, pointer.StringDeref(pls.Name, ""), pointer.StringDeref(peConn.Name, "")) + rerr := az.DeletePEConn(service, az.getPLSResourceGroup(service), pointer.StringDeref(pls.Name, ""), pointer.StringDeref(peConn.Name, "")) if rerr != nil { return rerr } } } - rerr := az.DeletePLS(service, pointer.StringDeref(pls.Name, ""), pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, "")) + rerr := az.DeletePLS(service, az.getPLSResourceGroup(service), pointer.StringDeref(pls.Name, ""), pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, "")) if rerr != nil { return rerr } @@ -402,11 +413,28 @@ func (az *Cloud) reconcilePLSIpConfigs( } if changed { + getFrontendIPConfigName := func(suffix string) (string, error) { + // frontend ipConfig name length cannot exceed 80 + maxPrefixLen := consts.FrontendIPConfigNameMaxLength - len(suffix) + if maxPrefixLen <= 0 { + return "", fmt.Errorf("reconcilePLSIpConfigs: frontend ipConfig suffix %s is too long (not likely to happen)", suffix) + } + prefix := fmt.Sprintf("%s-%s", pointer.StringDeref(subnet.Name, ""), pointer.StringDeref(existingPLS.Name, "")) + if len(prefix) > maxPrefixLen { + prefix = prefix[:maxPrefixLen] + } + return prefix + suffix, nil + } + ipConfigs := []network.PrivateLinkServiceIPConfiguration{} for k := range staticIps { ip := k isPrimary := strings.EqualFold(ip, primaryIP) - configName := fmt.Sprintf("%s-%s-static-%s", pointer.StringDeref(subnet.Name, ""), pointer.StringDeref(existingPLS.Name, ""), ip) + suffix := fmt.Sprintf("-static-%s", ip) + configName, err := getFrontendIPConfigName(suffix) + if err != nil { + return false, err + } ipConfigs = append(ipConfigs, network.PrivateLinkServiceIPConfiguration{ Name: &configName, PrivateLinkServiceIPConfigurationProperties: &network.PrivateLinkServiceIPConfigurationProperties{ @@ -422,7 +450,11 @@ func (az *Cloud) reconcilePLSIpConfigs( } for i := 0; i < int(ipConfigCount)-len(staticIps); i++ { isPrimary := primaryIP == "" && i == 0 - configName := fmt.Sprintf("%s-%s-dynamic-%d", pointer.StringDeref(subnet.Name, ""), pointer.StringDeref(existingPLS.Name, ""), i) + suffix := fmt.Sprintf("-dynamic-%d", i) + configName, err := getFrontendIPConfigName(suffix) + if err != nil { + return false, err + } ipConfigs = append(ipConfigs, network.PrivateLinkServiceIPConfiguration{ Name: &configName, PrivateLinkServiceIPConfigurationProperties: &network.PrivateLinkServiceIPConfigurationProperties{ diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice_repo.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice_repo.go index ae43681f0e..8dfe0cb8cc 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice_repo.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_privatelinkservice_repo.go @@ -18,6 +18,7 @@ package provider import ( "encoding/json" + "fmt" "net/http" "strings" "time" @@ -32,14 +33,14 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) -func (az *Cloud) CreateOrUpdatePLS(service *v1.Service, pls network.PrivateLinkService) error { +func (az *Cloud) CreateOrUpdatePLS(service *v1.Service, resourceGroup string, pls network.PrivateLinkService) error { ctx, cancel := getContextWithCancel() defer cancel() - rerr := az.PrivateLinkServiceClient.CreateOrUpdate(ctx, az.PrivateLinkServiceResourceGroup, pointer.StringDeref(pls.Name, ""), pls, pointer.StringDeref(pls.Etag, "")) + rerr := az.PrivateLinkServiceClient.CreateOrUpdate(ctx, resourceGroup, pointer.StringDeref(pls.Name, ""), pls, pointer.StringDeref(pls.Etag, "")) if rerr == nil { // Invalidate the cache right after updating - _ = az.plsCache.Delete(pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, "")) + _ = az.plsCache.Delete(getPLSCacheKey(resourceGroup, pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, ""))) return nil } @@ -49,26 +50,26 @@ func (az *Cloud) CreateOrUpdatePLS(service *v1.Service, pls network.PrivateLinkS // Invalidate the cache because etag mismatch. if rerr.HTTPStatusCode == http.StatusPreconditionFailed { klog.V(3).Infof("Private link service cache for %s is cleanup because of http.StatusPreconditionFailed", pointer.StringDeref(pls.Name, "")) - _ = az.plsCache.Delete(pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, "")) + _ = az.plsCache.Delete(getPLSCacheKey(resourceGroup, pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, ""))) } // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(rerr.Error().Error()), consts.OperationCanceledErrorMessage) { klog.V(3).Infof("Private link service for %s is cleanup because CreateOrUpdatePrivateLinkService is canceled by another operation", pointer.StringDeref(pls.Name, "")) - _ = az.plsCache.Delete(pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, "")) + _ = az.plsCache.Delete(getPLSCacheKey(resourceGroup, pointer.StringDeref((*pls.LoadBalancerFrontendIPConfigurations)[0].ID, ""))) } klog.Errorf("PrivateLinkServiceClient.CreateOrUpdate(%s) failed: %v", pointer.StringDeref(pls.Name, ""), rerr.Error()) return rerr.Error() } // DeletePLS invokes az.PrivateLinkServiceClient.Delete with exponential backoff retry -func (az *Cloud) DeletePLS(service *v1.Service, plsName string, plsLBFrontendID string) *retry.Error { +func (az *Cloud) DeletePLS(service *v1.Service, resourceGroup, plsName, plsLBFrontendID string) *retry.Error { ctx, cancel := getContextWithCancel() defer cancel() - rerr := az.PrivateLinkServiceClient.Delete(ctx, az.PrivateLinkServiceResourceGroup, plsName) + rerr := az.PrivateLinkServiceClient.Delete(ctx, resourceGroup, plsName) if rerr == nil { // Invalidate the cache right after deleting - _ = az.plsCache.Delete(plsLBFrontendID) + _ = az.plsCache.Delete(getPLSCacheKey(resourceGroup, plsLBFrontendID)) return nil } @@ -78,11 +79,11 @@ func (az *Cloud) DeletePLS(service *v1.Service, plsName string, plsLBFrontendID } // DeletePEConn invokes az.PrivateLinkServiceClient.DeletePEConnection with exponential backoff retry -func (az *Cloud) DeletePEConn(service *v1.Service, plsName string, peConnName string) *retry.Error { +func (az *Cloud) DeletePEConn(service *v1.Service, resourceGroup, plsName, peConnName string) *retry.Error { ctx, cancel := getContextWithCancel() defer cancel() - rerr := az.PrivateLinkServiceClient.DeletePEConnection(ctx, az.PrivateLinkServiceResourceGroup, plsName, peConnName) + rerr := az.PrivateLinkServiceClient.DeletePEConnection(ctx, resourceGroup, plsName, peConnName) if rerr == nil { return nil } @@ -97,7 +98,8 @@ func (az *Cloud) newPLSCache() (azcache.Resource, error) { getter := func(key string) (interface{}, error) { ctx, cancel := getContextWithCancel() defer cancel() - plsList, err := az.PrivateLinkServiceClient.List(ctx, az.PrivateLinkServiceResourceGroup) + resourceGroup, frontendID := parsePLSCacheKey(key) + plsList, err := az.PrivateLinkServiceClient.List(ctx, resourceGroup) exists, rerr := checkResourceExistsFromError(err) if rerr != nil { return nil, rerr.Error() @@ -114,7 +116,7 @@ func (az *Cloud) newPLSCache() (azcache.Resource, error) { continue } for _, fipConfig := range *fipConfigs { - if strings.EqualFold(*fipConfig.ID, key) { + if strings.EqualFold(*fipConfig.ID, frontendID) { return &pls, nil } } @@ -122,7 +124,7 @@ func (az *Cloud) newPLSCache() (azcache.Resource, error) { } } - klog.V(2).Infof("No privateLinkService found for frontendIPConfig %q", key) + klog.V(2).Infof("No privateLinkService found for frontendIPConfig %q in rg %q", frontendID, resourceGroup) plsNotExistID := consts.PrivateLinkServiceNotExistID return &network.PrivateLinkService{ID: &plsNotExistID}, nil } @@ -133,10 +135,19 @@ func (az *Cloud) newPLSCache() (azcache.Resource, error) { return azcache.NewTimedCache(time.Duration(az.PlsCacheTTLInSeconds)*time.Second, getter, az.Config.DisableAPICallCache) } -func (az *Cloud) getPrivateLinkService(frontendIPConfigID *string, crt azcache.AzureCacheReadType) (pls network.PrivateLinkService, err error) { - cachedPLS, err := az.plsCache.GetWithDeepCopy(*frontendIPConfigID, crt) +func (az *Cloud) getPrivateLinkService(resourceGroup string, frontendIPConfigID *string, crt azcache.AzureCacheReadType) (pls network.PrivateLinkService, err error) { + cachedPLS, err := az.plsCache.GetWithDeepCopy(getPLSCacheKey(resourceGroup, *frontendIPConfigID), crt) if err != nil { return pls, err } return *(cachedPLS.(*network.PrivateLinkService)), nil } + +func getPLSCacheKey(resourceGroup, plsLBFrontendID string) string { + return fmt.Sprintf("%s*%s", resourceGroup, plsLBFrontendID) +} + +func parsePLSCacheKey(key string) (string, string) { + splits := strings.Split(key, "*") + return splits[0], splits[1] +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_publicip_repo.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_publicip_repo.go index 2ace3b9925..bb24e1321c 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_publicip_repo.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_publicip_repo.go @@ -104,7 +104,7 @@ func (az *Cloud) newPIPCache() (azcache.Resource, error) { pipMap := &sync.Map{} for _, pip := range pipList { pip := pip - pipMap.Store(pointer.StringDeref(pip.Name, ""), &pip) + pipMap.Store(strings.ToLower(pointer.StringDeref(pip.Name, "")), &pip) } return pipMap, nil } @@ -122,7 +122,7 @@ func (az *Cloud) getPublicIPAddress(pipResourceGroup string, pipName string, crt } pips := cached.(*sync.Map) - pip, ok := pips.Load(pipName) + pip, ok := pips.Load(strings.ToLower(pipName)) if !ok { // pip not found, refresh cache and retry cached, err = az.pipCache.Get(pipResourceGroup, azcache.CacheReadTypeForceRefresh) @@ -130,7 +130,7 @@ func (az *Cloud) getPublicIPAddress(pipResourceGroup string, pipName string, crt return network.PublicIPAddress{}, false, err } pips = cached.(*sync.Map) - pip, ok = pips.Load(pipName) + pip, ok = pips.Load(strings.ToLower(pipName)) if !ok { return network.PublicIPAddress{}, false, nil } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_routes.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_routes.go index 4379531bf6..12c2bab472 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_routes.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_routes.go @@ -549,6 +549,10 @@ func cidrtoRfc1035(cidr string) string { // ensureRouteTableTagged ensures the route table is tagged as configured func (az *Cloud) ensureRouteTableTagged(rt *network.RouteTable) (map[string]*string, bool) { + if !strings.EqualFold(az.RouteTableResourceGroup, az.ResourceGroup) { + return nil, false + } + if az.Tags == "" && (az.TagsMap == nil || len(az.TagsMap) == 0) { return nil, false } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go index 1040317bec..5bc0b27ee0 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_standard.go @@ -54,14 +54,6 @@ var ( vmasIDRE = regexp.MustCompile(`/subscriptions/(?:.*)/resourceGroups/(?:.*)/providers/Microsoft.Compute/availabilitySets/(.+)`) ) -const ( - v6Suffix = "IPv6" -) - -var ( - v6SuffixLower = strings.ToLower(v6Suffix) -) - // returns the full identifier of an availabilitySet func (az *Cloud) getAvailabilitySetID(resourceGroup, availabilitySetName string) string { return fmt.Sprintf( @@ -270,7 +262,7 @@ func isInternalLoadBalancer(lb *network.LoadBalancer) bool { // clusters moving from IPv6 to dualstack will require no changes as the IPv4 backend pool will created with func getBackendPoolName(clusterName string, isIPv6 bool) string { if isIPv6 { - return fmt.Sprintf("%s-%s", clusterName, v6Suffix) + return fmt.Sprintf("%s-%s", clusterName, consts.IPVersionIPv6String) } return clusterName @@ -290,7 +282,7 @@ func isBackendPoolIPv6(name string) bool { } func managedResourceHasIPv6Suffix(name string) bool { - return strings.HasSuffix(strings.ToLower(name), fmt.Sprintf("-%s", v6SuffixLower)) + return strings.HasSuffix(strings.ToLower(name), fmt.Sprintf("-%s", consts.IPVersionIPv6StringLower)) } func (az *Cloud) getLoadBalancerRuleName(service *v1.Service, protocol v1.Protocol, port int32, isIPv6 bool) string { @@ -353,12 +345,6 @@ func (az *Cloud) getPublicIPName(clusterName string, service *v1.Service, isIPv6 return getResourceByIPFamily(pipName, isDualStack, isIPv6), nil } -// TODO: UT -func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool { - prefix := az.getRulePrefix(service) - return strings.HasPrefix(strings.ToUpper(rule), strings.ToUpper(prefix)) -} - func publicIPOwnsFrontendIP(service *v1.Service, fip *network.FrontendIPConfiguration, pip *network.PublicIPAddress) bool { if pip != nil && pip.ID != nil && @@ -523,8 +509,8 @@ func (as *availabilitySet) GetPowerStatusByNodeName(name string) (powerState str } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. - klog.V(3).Infof("InstanceView for node %q is nil, assuming it's stopped", name) - return vmPowerStateStopped, nil + klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) + return vmPowerStateUnknown, nil } // GetProvisioningStateByNodeName returns the provisioningState for the specified node. diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go index ee0fe7db91..127c1b07c5 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_storageaccount.go @@ -56,7 +56,7 @@ type AccountOptions struct { EnableHTTPSTrafficOnly bool // indicate whether create new account when Name is empty or when account does not exists CreateAccount bool - CreatePrivateEndpoint bool + CreatePrivateEndpoint *bool StorageType StorageType StorageEndpointSuffix string DisableFileServiceDeleteRetentionPolicy *bool @@ -216,7 +216,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } var privateDNSZoneName string - if accountOptions.CreatePrivateEndpoint { + if pointer.BoolDeref(accountOptions.CreatePrivateEndpoint, false) { if accountOptions.StorageType == "" { klog.V(2).Info("set StorageType as file when not specified") accountOptions.StorageType = StorageTypeFile @@ -282,7 +282,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } } - if accountOptions.CreatePrivateEndpoint { + if pointer.BoolDeref(accountOptions.CreatePrivateEndpoint, false) { if _, err := az.privatednsclient.Get(ctx, vnetResourceGroup, privateDNSZoneName); err != nil { klog.V(2).Infof("get private dns zone %s returned with %v", privateDNSZoneName, err.Error()) // Create DNS zone first, this could make sure driver has write permission on vnetResourceGroup @@ -320,7 +320,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } } - if accountOptions.CreatePrivateEndpoint { + if pointer.BoolDeref(accountOptions.CreatePrivateEndpoint, false) { networkRuleSet = &storage.NetworkRuleSet{ DefaultAction: storage.DefaultActionDeny, } @@ -471,7 +471,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } } - if accountOptions.CreatePrivateEndpoint { + if pointer.BoolDeref(accountOptions.CreatePrivateEndpoint, false) { // Get properties of the storageAccount storageAccount, err := az.StorageAccountClient.GetProperties(ctx, subsID, resourceGroup, accountName) if err != nil { @@ -625,11 +625,16 @@ func (az *Cloud) getStorageAccountWithCache(ctx context.Context, subsID, resourc // AddStorageAccountTags add tags to storage account func (az *Cloud) AddStorageAccountTags(ctx context.Context, subsID, resourceGroup, account string, tags map[string]*string) *retry.Error { + // add lock to avoid concurrent update on the cache + az.lockMap.LockEntry(account) + defer az.lockMap.UnlockEntry(account) + result, rerr := az.getStorageAccountWithCache(ctx, subsID, resourceGroup, account) if rerr != nil { return rerr } + originalLen := len(result.Tags) newTags := result.Tags if newTags == nil { newTags = make(map[string]*string) @@ -640,10 +645,11 @@ func (az *Cloud) AddStorageAccountTags(ctx context.Context, subsID, resourceGrou newTags[k] = v } - if len(newTags) > len(result.Tags) { + if len(newTags) > originalLen { // only update when newTags is different from old tags _ = az.storageAccountCache.Delete(account) // clean cache updateParams := storage.AccountUpdateParameters{Tags: newTags} + klog.V(2).Infof("update storage account(%s) with tags(%+v)", account, newTags) return az.StorageAccountClient.Update(ctx, subsID, resourceGroup, account, updateParams) } return nil @@ -651,6 +657,10 @@ func (az *Cloud) AddStorageAccountTags(ctx context.Context, subsID, resourceGrou // RemoveStorageAccountTag remove tag from storage account func (az *Cloud) RemoveStorageAccountTag(ctx context.Context, subsID, resourceGroup, account, key string) *retry.Error { + // add lock to avoid concurrent update on the cache + az.lockMap.LockEntry(account) + defer az.lockMap.UnlockEntry(account) + result, rerr := az.getStorageAccountWithCache(ctx, subsID, resourceGroup, account) if rerr != nil { return rerr @@ -770,10 +780,15 @@ func isEnableNfsV3PropertyEqual(account storage.Account, accountOptions *Account } func isPrivateEndpointAsExpected(account storage.Account, accountOptions *AccountOptions) bool { - if accountOptions.CreatePrivateEndpoint && account.PrivateEndpointConnections != nil && len(*account.PrivateEndpointConnections) > 0 { + if accountOptions.CreatePrivateEndpoint == nil { + // CreatePrivateEndpoint is not set, match current account + return true + } + + if pointer.BoolDeref(accountOptions.CreatePrivateEndpoint, false) && account.PrivateEndpointConnections != nil && len(*account.PrivateEndpointConnections) > 0 { return true } - if !accountOptions.CreatePrivateEndpoint && (account.PrivateEndpointConnections == nil || len(*account.PrivateEndpointConnections) == 0) { + if !pointer.BoolDeref(accountOptions.CreatePrivateEndpoint, false) && (account.PrivateEndpointConnections == nil || len(*account.PrivateEndpointConnections) == 0) { return true } return false diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go index e8724ef6a5..9651be53b7 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_utils.go @@ -404,7 +404,7 @@ func setServiceLoadBalancerIP(service *v1.Service, ip string) { } parsedIP := net.ParseIP(ip) if parsedIP == nil { - klog.Warning("setServiceLoadBalancerIP: IP %q is not valid for Service", ip, service.Name) + klog.Warningf("setServiceLoadBalancerIP: IP %q is not valid for Service %q", ip, service.Name) return } @@ -453,7 +453,7 @@ func getServicePIPPrefixID(service *v1.Service, isIPv6 bool) string { // the old PIPs will be recreated. func getResourceByIPFamily(resource string, isDualStack, isIPv6 bool) string { if isDualStack && isIPv6 { - return fmt.Sprintf("%s-%s", resource, v6Suffix) + return fmt.Sprintf("%s-%s", resource, consts.IPVersionIPv6String) } return resource } @@ -604,3 +604,18 @@ func getServiceIPFamily(service *v1.Service) string { } return consts.IPVersionIPv4String } + +// getResourceGroupAndNameFromNICID parses the ip configuration ID to get the resource group and nic name. +func getResourceGroupAndNameFromNICID(ipConfigurationID string) (string, string, error) { + matches := nicIDRE.FindStringSubmatch(ipConfigurationID) + if len(matches) != 3 { + klog.V(4).Infof("Can not extract nic name from ipConfigurationID (%s)", ipConfigurationID) + return "", "", fmt.Errorf("invalid ip config ID %s", ipConfigurationID) + } + + nicResourceGroup, nicName := matches[1], matches[2] + if nicResourceGroup == "" || nicName == "" { + return "", "", fmt.Errorf("invalid ip config ID %s", ipConfigurationID) + } + return nicResourceGroup, nicName, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go index 24b29ac81b..5ab2b996bb 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss.go @@ -293,8 +293,8 @@ func (ss *ScaleSet) GetPowerStatusByNodeName(name string) (powerState string, er } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. - klog.V(3).Infof("InstanceView for node %q is nil, assuming it's stopped", name) - return vmPowerStateStopped, nil + klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) + return vmPowerStateUnknown, nil } // GetProvisioningStateByNodeName returns the provisioningState for the specified node. diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go index 860fead7a9..592e05d168 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmss_cache.go @@ -288,7 +288,7 @@ func (ss *ScaleSet) DeleteCacheForNode(nodeName string) error { } func (ss *ScaleSet) updateCache(nodeName, resourceGroupName, vmssName, instanceID string, updatedVM *compute.VirtualMachineScaleSetVM) error { - if ss.common.DisableUpdateCache { + if ss.ManagedDiskController.DisableUpdateCache { return nil } // lock the VMSS entry to ensure a consistent view of the VM map when there are concurrent updates. @@ -467,6 +467,12 @@ func (ss *ScaleSet) getVMManagementTypeByProviderID(providerID string, crt azcac } +// getVMManagementTypeByIPConfigurationID determines the VM type by the following steps: +// 1. If the ipConfigurationID is in the format of vmssIPConfigurationRE, returns vmss uniform. +// 2. If the name of the VM can be obtained by trimming the `-nic` suffix from the nic name, and the VM name is in the +// VMAS cache, returns availability set. +// 3. If the VM name obtained from step 2 is not in the VMAS cache, try to get the VM name from NIC.VirtualMachine.ID. +// 4. If the VM name obtained from step 3 is in the VMAS cache, returns availability set. Or, returns vmss flex. func (ss *ScaleSet) getVMManagementTypeByIPConfigurationID(ipConfigurationID string, crt azcache.AzureCacheReadType) (VMManagementType, error) { if ss.DisableAvailabilitySetNodes && !ss.EnableVmssFlexNodes { return ManagedByVmssUniform, nil @@ -484,16 +490,11 @@ func (ss *ScaleSet) getVMManagementTypeByIPConfigurationID(ipConfigurationID str return ManagedByUnknownVMSet, err } - matches := nicIDRE.FindStringSubmatch(ipConfigurationID) - if len(matches) != 3 { + nicResourceGroup, nicName, err := getResourceGroupAndNameFromNICID(ipConfigurationID) + if err != nil { return ManagedByUnknownVMSet, fmt.Errorf("can not extract nic name from ipConfigurationID (%s)", ipConfigurationID) } - nicResourceGroup, nicName := matches[1], matches[2] - if nicResourceGroup == "" || nicName == "" { - return ManagedByUnknownVMSet, fmt.Errorf("invalid ip config ID %s", ipConfigurationID) - } - vmName := strings.Replace(nicName, "-nic", "", 1) cachedAvSetVMs := cached.(NonVmssUniformNodesEntry).AvSetVMNodeNames @@ -501,5 +502,35 @@ func (ss *ScaleSet) getVMManagementTypeByIPConfigurationID(ipConfigurationID str if cachedAvSetVMs.Has(vmName) { return ManagedByAvSet, nil } + + // Get the vmName by nic.VirtualMachine.ID if the vmName is not in the format + // of `vmName-nic`. This introduces an extra ARM call. + vmName, err = ss.GetVMNameByIPConfigurationName(nicResourceGroup, nicName) + if err != nil { + return ManagedByUnknownVMSet, fmt.Errorf("failed to get vm name by ip config ID %s: %w", ipConfigurationID, err) + } + if cachedAvSetVMs.Has(vmName) { + return ManagedByAvSet, nil + } + return ManagedByVmssFlex, nil } + +func (az *Cloud) GetVMNameByIPConfigurationName(nicResourceGroup, nicName string) (string, error) { + ctx, cancel := getContextWithCancel() + defer cancel() + nic, rerr := az.InterfacesClient.Get(ctx, nicResourceGroup, nicName, "") + if rerr != nil { + return "", fmt.Errorf("failed to get interface of name %s: %w", nicName, rerr.Error()) + } + if nic.InterfacePropertiesFormat == nil || nic.InterfacePropertiesFormat.VirtualMachine == nil || nic.InterfacePropertiesFormat.VirtualMachine.ID == nil { + return "", fmt.Errorf("failed to get vm ID of nic %s", pointer.StringDeref(nic.Name, "")) + } + vmID := pointer.StringDeref(nic.InterfacePropertiesFormat.VirtualMachine.ID, "") + matches := vmIDRE.FindStringSubmatch(vmID) + if len(matches) != 2 { + return "", fmt.Errorf("invalid virtual machine ID %s", vmID) + } + vmName := matches[1] + return vmName, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go index 22889373be..42202a5af7 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmssflex.go @@ -279,8 +279,8 @@ func (fs *FlexScaleSet) GetPowerStatusByNodeName(name string) (powerState string } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. - klog.V(3).Infof("InstanceView for node %q is nil, assuming it's stopped", name) - return vmPowerStateStopped, nil + klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) + return vmPowerStateUnknown, nil } // GetPrimaryInterface gets machine primary network interface by node name. @@ -384,33 +384,16 @@ func (fs *FlexScaleSet) GetNodeNameByIPConfigurationID(ipConfigurationID string) } func (fs *FlexScaleSet) getNodeInformationByIPConfigurationID(ipConfigurationID string) (string, string, string, error) { - matches := nicIDRE.FindStringSubmatch(ipConfigurationID) - if len(matches) != 3 { - klog.V(4).Infof("Can not extract nic name from ipConfigurationID (%s)", ipConfigurationID) - return "", "", "", fmt.Errorf("invalid ip config ID %s", ipConfigurationID) - } - - nicResourceGroup, nicName := matches[1], matches[2] - if nicResourceGroup == "" || nicName == "" { - return "", "", "", fmt.Errorf("invalid ip config ID %s", ipConfigurationID) + nicResourceGroup, nicName, err := getResourceGroupAndNameFromNICID(ipConfigurationID) + if err != nil { + return "", "", "", fmt.Errorf("failed to get resource group and name from ip config ID %s: %w", ipConfigurationID, err) } // get vmName by nic name - ctx, cancel := getContextWithCancel() - defer cancel() - nic, rerr := fs.InterfacesClient.Get(ctx, nicResourceGroup, nicName, "") - if rerr != nil { - return "", "", "", fmt.Errorf("getNodeInformationByIPConfigurationID(%s): failed to get interface of name %s: %w", ipConfigurationID, nicName, rerr.Error()) - } - if nic.InterfacePropertiesFormat == nil || nic.InterfacePropertiesFormat.VirtualMachine == nil || nic.InterfacePropertiesFormat.VirtualMachine.ID == nil { - return "", "", "", fmt.Errorf("failed to get vm ID of ip config ID %s", ipConfigurationID) - } - vmID := pointer.StringDeref(nic.InterfacePropertiesFormat.VirtualMachine.ID, "") - matches = vmIDRE.FindStringSubmatch(vmID) - if len(matches) != 2 { - return "", "", "", fmt.Errorf("invalid virtual machine ID %s", vmID) + vmName, err := fs.GetVMNameByIPConfigurationName(nicResourceGroup, nicName) + if err != nil { + return "", "", "", fmt.Errorf("failed to get vm name of ip config ID %s", ipConfigurationID) } - vmName := matches[1] nodeName, err := fs.getNodeNameByVMName(vmName) if err != nil { diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_wrap.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_wrap.go index 1675aa12e9..cb7dd54f94 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_wrap.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_wrap.go @@ -97,3 +97,7 @@ func ConvertResourceGroupNameToLower(resourceID string) (string, error) { resourceGroup := matches[1] return strings.Replace(resourceID, resourceGroup, strings.ToLower(resourceGroup), 1), nil } + +func (az *Cloud) useSharedLoadBalancerHealthProbeMode() bool { + return strings.EqualFold(az.ClusterServiceLoadBalancerHealthProbeMode, consts.ClusterServiceLoadBalancerHealthProbeModeShared) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/accesscontrol.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/accesscontrol.go new file mode 100644 index 0000000000..c717584694 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/accesscontrol.go @@ -0,0 +1,202 @@ +/* +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 loadbalancer + +import ( + "fmt" + "net/netip" + "strings" + + v1 "k8s.io/api/core/v1" + + "sigs.k8s.io/cloud-provider-azure/pkg/consts" +) + +// IsInternal returns true if the given service is internal load balancer. +func IsInternal(svc *v1.Service) bool { + value, found := svc.Annotations[consts.ServiceAnnotationLoadBalancerInternal] + return found && strings.ToLower(value) == "true" +} + +// IsExternal returns true if the given service is external load balancer. +func IsExternal(svc *v1.Service) bool { + return !IsInternal(svc) +} + +// AllowedServiceTags returns the allowed service tags configured by user through AKS custom annotation. +func AllowedServiceTags(svc *v1.Service) ([]string, error) { + const Sep = "," + + value, found := svc.Annotations[consts.ServiceAnnotationAllowedServiceTags] + if !found { + return nil, nil + } + + return strings.Split(strings.TrimSpace(value), Sep), nil +} + +// AllowedIPRanges returns the allowed IP ranges configured by user through AKS custom annotation. +func AllowedIPRanges(svc *v1.Service) ([]netip.Prefix, error) { + const Sep = "," + + value, found := svc.Annotations[consts.ServiceAnnotationAllowedIPRanges] + if !found { + return nil, nil + } + + rv, err := ParseCIDRs(strings.Split(strings.TrimSpace(value), Sep)) + if err != nil { + return nil, fmt.Errorf("invalid service annotation %s:%s: %w", consts.ServiceAnnotationAllowedIPRanges, value, err) + } + + return rv, nil +} + +// SourceRanges returns the allowed IP ranges configured by user through `spec.LoadBalancerSourceRanges` and standard annotation. +// If `spec.LoadBalancerSourceRanges` is not set, it will try to parse the annotation. +func SourceRanges(svc *v1.Service) ([]netip.Prefix, error) { + if len(svc.Spec.LoadBalancerSourceRanges) > 0 { + rv, err := ParseCIDRs(svc.Spec.LoadBalancerSourceRanges) + if err != nil { + return nil, fmt.Errorf("invalid service.Spec.LoadBalancerSourceRanges [%v]: %w", svc.Spec.LoadBalancerSourceRanges, err) + } + return rv, nil + } + + const Sep = "," + value, found := svc.Annotations[v1.AnnotationLoadBalancerSourceRangesKey] + if !found { + return nil, nil + } + rv, err := ParseCIDRs(strings.Split(strings.TrimSpace(value), Sep)) + if err != nil { + return nil, fmt.Errorf("invalid service annotation %s:%s: %w", v1.AnnotationLoadBalancerSourceRangesKey, value, err) + } + return rv, nil +} + +type AccessControl struct { + svc *v1.Service + + // immutable redundant states. + sourceRanges []netip.Prefix + allowedIPRanges []netip.Prefix + allowedServiceTags []string +} + +func NewAccessControl(svc *v1.Service) (*AccessControl, error) { + sourceRanges, err := SourceRanges(svc) + if err != nil { + return nil, err + } + allowedIPRanges, err := AllowedIPRanges(svc) + if err != nil { + return nil, err + } + allowedServiceTags, err := AllowedServiceTags(svc) + if err != nil { + return nil, err + } + + return &AccessControl{ + svc: svc, + sourceRanges: sourceRanges, + allowedIPRanges: allowedIPRanges, + allowedServiceTags: allowedServiceTags, + }, nil +} + +// SourceRanges returns the allowed IP ranges configured by user through `spec.LoadBalancerSourceRanges` and standard annotation. +func (ac *AccessControl) SourceRanges() []netip.Prefix { + return ac.sourceRanges +} + +// AllowedIPRanges returns the allowed IP ranges configured by user through AKS custom annotation. +func (ac *AccessControl) AllowedIPRanges() []netip.Prefix { + return ac.allowedIPRanges +} + +// AllowedServiceTags returns the allowed service tags configured by user through AKS custom annotation. +func (ac *AccessControl) AllowedServiceTags() []string { + return ac.allowedServiceTags +} + +// IsAllowFromInternet returns true if the given service is allowed to be accessed from internet. +// To be specific, +// 1. For all types of LB, it returns false if the given service is specified with `service tags` or `not allowed all IP ranges`. +// 2. For internal LB, it returns true iff the given service is explicitly specified with `allowed all IP ranges`. Refer: https://github.com/kubernetes-sigs/cloud-provider-azure/issues/698 +func (ac *AccessControl) IsAllowFromInternet() bool { + if len(ac.allowedServiceTags) > 0 { + return false + } + if len(ac.sourceRanges) > 0 && !IsCIDRsAllowAll(ac.sourceRanges) { + return false + } + if len(ac.allowedIPRanges) > 0 && !IsCIDRsAllowAll(ac.allowedIPRanges) { + return false + } + if IsExternal(ac.svc) { + return true + } + // Internal LB with explicit allowedAll IP ranges is allowed to be accessed from internet. + return len(ac.allowedIPRanges) > 0 || len(ac.sourceRanges) > 0 +} + +// IPV4Sources returns the allowed sources for IPv4. +func (ac *AccessControl) IPV4Sources() []string { + var rv []string + + if ac.IsAllowFromInternet() { + rv = append(rv, "Internet") + } + for _, cidr := range ac.sourceRanges { + if cidr.Addr().Is4() { + rv = append(rv, cidr.String()) + } + } + for _, cidr := range ac.allowedIPRanges { + if cidr.Addr().Is4() { + rv = append(rv, cidr.String()) + } + } + rv = append(rv, ac.allowedServiceTags...) + + return rv +} + +// IPV6Sources returns the allowed sources for IPv6. +func (ac *AccessControl) IPV6Sources() []string { + var ( + rv []string + ) + if ac.IsAllowFromInternet() { + rv = append(rv, "Internet") + } + for _, cidr := range ac.sourceRanges { + if cidr.Addr().Is6() { + rv = append(rv, cidr.String()) + } + } + for _, cidr := range ac.allowedIPRanges { + if cidr.Addr().Is6() { + rv = append(rv, cidr.String()) + } + } + rv = append(rv, ac.allowedServiceTags...) + + return rv +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/netip.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/netip.go new file mode 100644 index 0000000000..c7e4632b6e --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer/netip.go @@ -0,0 +1,50 @@ +/* +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 loadbalancer + +import ( + "fmt" + "net/netip" +) + +const ( + IPv4AllowedAll = "0.0.0.0/0" + IPv6AllowedAll = "::/0" +) + +// IsCIDRsAllowAll return true if the given IP Ranges covers all IPs. +// It returns false if the given IP Ranges is empty. +func IsCIDRsAllowAll(cidrs []netip.Prefix) bool { + for _, cidr := range cidrs { + if cidr.String() == IPv4AllowedAll || cidr.String() == IPv6AllowedAll { + return true + } + } + return false +} + +func ParseCIDRs(parts []string) ([]netip.Prefix, error) { + var rv []netip.Prefix + for _, part := range parts { + prefix, err := netip.ParsePrefix(part) + if err != nil { + return nil, fmt.Errorf("invalid IP range %s: %w", part, err) + } + rv = append(rv, prefix) + } + return rv, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/taints/taints.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/taints/taints.go new file mode 100644 index 0000000000..2c826f43be --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/util/taints/taints.go @@ -0,0 +1,29 @@ +/* +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 taints + +import v1 "k8s.io/api/core/v1" + +// TaintExists checks if the given taint exists in list of taints. Returns true if exists false otherwise. +func TaintExists(taints []v1.Taint, taintToFind *v1.Taint) bool { + for _, taint := range taints { + if taint.MatchTaint(taintToFind) { + return true + } + } + return false +} diff --git a/vendor/sigs.k8s.io/yaml/LICENSE b/vendor/sigs.k8s.io/yaml/LICENSE index 7805d36de7..093d6d3edf 100644 --- a/vendor/sigs.k8s.io/yaml/LICENSE +++ b/vendor/sigs.k8s.io/yaml/LICENSE @@ -48,3 +48,259 @@ 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. + +# The forked go-yaml.v3 library under this project is covered by two +different licenses (MIT and Apache): + +#### MIT License #### + +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original MIT license, with the additional +copyright staring in 2011 when the project was ported over: + + apic.go emitterc.go parserc.go readerc.go scannerc.go + writerc.go yamlh.go yamlprivateh.go + +Copyright (c) 2006-2010 Kirill Simonov +Copyright (c) 2006-2011 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +### Apache License ### + +All the remaining project files are covered by the Apache license: + +Copyright (c) 2011-2019 Canonical Ltd + +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. + +# The forked go-yaml.v2 library under the project is covered by an +Apache license: + + 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 + + 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. diff --git a/vendor/sigs.k8s.io/yaml/OWNERS b/vendor/sigs.k8s.io/yaml/OWNERS index 325b40b076..003a149e15 100644 --- a/vendor/sigs.k8s.io/yaml/OWNERS +++ b/vendor/sigs.k8s.io/yaml/OWNERS @@ -2,26 +2,22 @@ approvers: - dims -- lavalamp +- jpbetz - smarterclayton - deads2k - sttts - liggitt -- caesarxuchao reviewers: - dims - thockin -- lavalamp +- jpbetz - smarterclayton - wojtek-t - deads2k - derekwaynecarr -- caesarxuchao - mikedanese - liggitt -- gmarek - sttts -- ncdc - tallclair labels: - sig/api-machinery diff --git a/vendor/sigs.k8s.io/yaml/fields.go b/vendor/sigs.k8s.io/yaml/fields.go index 235b7f2cf6..0ea28bd030 100644 --- a/vendor/sigs.k8s.io/yaml/fields.go +++ b/vendor/sigs.k8s.io/yaml/fields.go @@ -16,53 +16,53 @@ import ( "unicode/utf8" ) -// indirect walks down v allocating pointers as needed, +// indirect walks down 'value' allocating pointers as needed, // until it gets to a non-pointer. // if it encounters an Unmarshaler, indirect stops and returns that. // if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, +func indirect(value reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { + // If 'value' is a named type and is addressable, // start with its address, so that if the type has pointer methods, // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() + if value.Kind() != reflect.Ptr && value.Type().Name() != "" && value.CanAddr() { + value = value.Addr() } for { // Load value from interface, but only if the result will be // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e + if value.Kind() == reflect.Interface && !value.IsNil() { + element := value.Elem() + if element.Kind() == reflect.Ptr && !element.IsNil() && (!decodingNull || element.Elem().Kind() == reflect.Ptr) { + value = element continue } } - if v.Kind() != reflect.Ptr { + if value.Kind() != reflect.Ptr { break } - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { + if value.Elem().Kind() != reflect.Ptr && decodingNull && value.CanSet() { break } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) + if value.IsNil() { + if value.CanSet() { + value.Set(reflect.New(value.Type().Elem())) } else { - v = reflect.New(v.Type().Elem()) + value = reflect.New(value.Type().Elem()) } } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { + if value.Type().NumMethod() > 0 { + if u, ok := value.Interface().(json.Unmarshaler); ok { return u, nil, reflect.Value{} } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { + if u, ok := value.Interface().(encoding.TextUnmarshaler); ok { return nil, u, reflect.Value{} } } - v = v.Elem() + value = value.Elem() } - return nil, nil, v + return nil, nil, value } // A field represents a single field found in a struct. @@ -134,8 +134,8 @@ func typeFields(t reflect.Type) []field { next := []field{{typ: t}} // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} + var count map[reflect.Type]int + var nextCount map[reflect.Type]int // Types already visited at an earlier level. visited := map[reflect.Type]bool{} @@ -348,8 +348,9 @@ const ( // 4) simpleLetterEqualFold, no specials, no non-letters. // // The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign +// - S maps to s and to U+017F 'ſ' Latin small letter long s +// - k maps to K and to U+212A 'K' Kelvin sign +// // See http://play.golang.org/p/tTxjOc0OGo // // The returned function is specialized for matching against s and @@ -420,10 +421,8 @@ func equalFoldRight(s, t []byte) bool { t = t[size:] } - if len(t) > 0 { - return false - } - return true + + return len(t) <= 0 } // asciiEqualFold is a specialization of bytes.EqualFold for use when diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE b/vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE new file mode 100644 index 0000000000..8dada3edaf --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE @@ -0,0 +1,201 @@ + 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 + + 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. diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE.libyaml b/vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE.libyaml new file mode 100644 index 0000000000..8da58fbf6f --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/LICENSE.libyaml @@ -0,0 +1,31 @@ +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original copyright and license: + + apic.go + emitterc.go + parserc.go + readerc.go + scannerc.go + writerc.go + yamlh.go + yamlprivateh.go + +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/NOTICE b/vendor/sigs.k8s.io/yaml/goyaml.v2/NOTICE new file mode 100644 index 0000000000..866d74a7ad --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +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/sigs.k8s.io/yaml/goyaml.v2/OWNERS b/vendor/sigs.k8s.io/yaml/goyaml.v2/OWNERS new file mode 100644 index 0000000000..73be0a3a9b --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/OWNERS @@ -0,0 +1,24 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +approvers: +- dims +- jpbetz +- smarterclayton +- deads2k +- sttts +- liggitt +- natasha41575 +- knverey +reviewers: +- dims +- thockin +- jpbetz +- smarterclayton +- deads2k +- derekwaynecarr +- mikedanese +- liggitt +- sttts +- tallclair +labels: +- sig/api-machinery diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/README.md b/vendor/sigs.k8s.io/yaml/goyaml.v2/README.md new file mode 100644 index 0000000000..53f4139dc3 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/README.md @@ -0,0 +1,143 @@ +# go-yaml fork + +This package is a fork of the go-yaml library and is intended solely for consumption +by kubernetes projects. In this fork, we plan to support only critical changes required for +kubernetes, such as small bug fixes and regressions. Larger, general-purpose feature requests +should be made in the upstream go-yaml library, and we will reject such changes in this fork +unless we are pulling them from upstream. + +This fork is based on v2.4.0: https://github.com/go-yaml/yaml/releases/tag/v2.4.0 + +# YAML support for the Go language + +Introduction +------------ + +The yaml package enables Go programs to comfortably encode and decode YAML +values. It was developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a +pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) +C library to parse and generate YAML data quickly and reliably. + +Compatibility +------------- + +The yaml package supports most of YAML 1.1 and 1.2, including support for +anchors, tags, map merging, etc. Multi-document unmarshalling is not yet +implemented, and base-60 floats from YAML 1.1 are purposefully not +supported since they're a poor design and are gone in YAML 1.2. + +Installation and usage +---------------------- + +The import path for the package is *gopkg.in/yaml.v2*. + +To install it, run: + + go get gopkg.in/yaml.v2 + +API documentation +----------------- + +If opened in a browser, the import path itself leads to the API documentation: + + * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) + +API stability +------------- + +The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). + + +License +------- + +The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. + + +Example +------- + +```Go +package main + +import ( + "fmt" + "log" + + "gopkg.in/yaml.v2" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/apic.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/apic.go new file mode 100644 index 0000000000..acf71402cf --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/apic.go @@ -0,0 +1,744 @@ +package yaml + +import ( + "io" +) + +func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { + //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + + // Check if we can move the queue at the beginning of the buffer. + if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { + if parser.tokens_head != len(parser.tokens) { + copy(parser.tokens, parser.tokens[parser.tokens_head:]) + } + parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] + parser.tokens_head = 0 + } + parser.tokens = append(parser.tokens, *token) + if pos < 0 { + return + } + copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) + parser.tokens[parser.tokens_head+pos] = *token +} + +// Create a new parser object. +func yaml_parser_initialize(parser *yaml_parser_t) bool { + *parser = yaml_parser_t{ + raw_buffer: make([]byte, 0, input_raw_buffer_size), + buffer: make([]byte, 0, input_buffer_size), + } + return true +} + +// Destroy a parser object. +func yaml_parser_delete(parser *yaml_parser_t) { + *parser = yaml_parser_t{} +} + +// String read handler. +func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + if parser.input_pos == len(parser.input) { + return 0, io.EOF + } + n = copy(buffer, parser.input[parser.input_pos:]) + parser.input_pos += n + return n, nil +} + +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) +} + +// Set a string input. +func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_string_read_handler + parser.input = input + parser.input_pos = 0 +} + +// Set a file input. +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { + if parser.read_handler != nil { + panic("must set the input source only once") + } + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r +} + +// Set the source encoding. +func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { + if parser.encoding != yaml_ANY_ENCODING { + panic("must set the encoding only once") + } + parser.encoding = encoding +} + +var disableLineWrapping = false + +// Create a new emitter object. +func yaml_emitter_initialize(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{ + buffer: make([]byte, output_buffer_size), + raw_buffer: make([]byte, 0, output_raw_buffer_size), + states: make([]yaml_emitter_state_t, 0, initial_stack_size), + events: make([]yaml_event_t, 0, initial_queue_size), + } + if disableLineWrapping { + emitter.best_width = -1 + } +} + +// Destroy an emitter object. +func yaml_emitter_delete(emitter *yaml_emitter_t) { + *emitter = yaml_emitter_t{} +} + +// String write handler. +func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + *emitter.output_buffer = append(*emitter.output_buffer, buffer...) + return nil +} + +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) + return err +} + +// Set a string output. +func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_string_write_handler + emitter.output_buffer = output_buffer +} + +// Set a file output. +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { + if emitter.write_handler != nil { + panic("must set the output target only once") + } + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w +} + +// Set the output encoding. +func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { + if emitter.encoding != yaml_ANY_ENCODING { + panic("must set the output encoding only once") + } + emitter.encoding = encoding +} + +// Set the canonical output style. +func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { + emitter.canonical = canonical +} + +//// Set the indentation increment. +func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { + if indent < 2 || indent > 9 { + indent = 2 + } + emitter.best_indent = indent +} + +// Set the preferred line width. +func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { + if width < 0 { + width = -1 + } + emitter.best_width = width +} + +// Set if unescaped non-ASCII characters are allowed. +func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { + emitter.unicode = unicode +} + +// Set the preferred line break character. +func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { + emitter.line_break = line_break +} + +///* +// * Destroy a token object. +// */ +// +//YAML_DECLARE(void) +//yaml_token_delete(yaml_token_t *token) +//{ +// assert(token); // Non-NULL token object expected. +// +// switch (token.type) +// { +// case YAML_TAG_DIRECTIVE_TOKEN: +// yaml_free(token.data.tag_directive.handle); +// yaml_free(token.data.tag_directive.prefix); +// break; +// +// case YAML_ALIAS_TOKEN: +// yaml_free(token.data.alias.value); +// break; +// +// case YAML_ANCHOR_TOKEN: +// yaml_free(token.data.anchor.value); +// break; +// +// case YAML_TAG_TOKEN: +// yaml_free(token.data.tag.handle); +// yaml_free(token.data.tag.suffix); +// break; +// +// case YAML_SCALAR_TOKEN: +// yaml_free(token.data.scalar.value); +// break; +// +// default: +// break; +// } +// +// memset(token, 0, sizeof(yaml_token_t)); +//} +// +///* +// * Check if a string is a valid UTF-8 sequence. +// * +// * Check 'reader.c' for more details on UTF-8 encoding. +// */ +// +//static int +//yaml_check_utf8(yaml_char_t *start, size_t length) +//{ +// yaml_char_t *end = start+length; +// yaml_char_t *pointer = start; +// +// while (pointer < end) { +// unsigned char octet; +// unsigned int width; +// unsigned int value; +// size_t k; +// +// octet = pointer[0]; +// width = (octet & 0x80) == 0x00 ? 1 : +// (octet & 0xE0) == 0xC0 ? 2 : +// (octet & 0xF0) == 0xE0 ? 3 : +// (octet & 0xF8) == 0xF0 ? 4 : 0; +// value = (octet & 0x80) == 0x00 ? octet & 0x7F : +// (octet & 0xE0) == 0xC0 ? octet & 0x1F : +// (octet & 0xF0) == 0xE0 ? octet & 0x0F : +// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; +// if (!width) return 0; +// if (pointer+width > end) return 0; +// for (k = 1; k < width; k ++) { +// octet = pointer[k]; +// if ((octet & 0xC0) != 0x80) return 0; +// value = (value << 6) + (octet & 0x3F); +// } +// if (!((width == 1) || +// (width == 2 && value >= 0x80) || +// (width == 3 && value >= 0x800) || +// (width == 4 && value >= 0x10000))) return 0; +// +// pointer += width; +// } +// +// return 1; +//} +// + +// Create STREAM-START. +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + encoding: encoding, + } +} + +// Create STREAM-END. +func yaml_stream_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + } +} + +// Create DOCUMENT-START. +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: implicit, + } +} + +// Create DOCUMENT-END. +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + implicit: implicit, + } +} + +///* +// * Create ALIAS. +// */ +// +//YAML_DECLARE(int) +//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) +//{ +// mark yaml_mark_t = { 0, 0, 0 } +// anchor_copy *yaml_char_t = NULL +// +// assert(event) // Non-NULL event object is expected. +// assert(anchor) // Non-NULL anchor is expected. +// +// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 +// +// anchor_copy = yaml_strdup(anchor) +// if (!anchor_copy) +// return 0 +// +// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) +// +// return 1 +//} + +// Create SCALAR. +func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + anchor: anchor, + tag: tag, + value: value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-START. +func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } + return true +} + +// Create SEQUENCE-END. +func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + } + return true +} + +// Create MAPPING-START. +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(style), + } +} + +// Create MAPPING-END. +func yaml_mapping_end_event_initialize(event *yaml_event_t) { + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + } +} + +// Destroy an event object. +func yaml_event_delete(event *yaml_event_t) { + *event = yaml_event_t{} +} + +///* +// * Create a document object. +// */ +// +//YAML_DECLARE(int) +//yaml_document_initialize(document *yaml_document_t, +// version_directive *yaml_version_directive_t, +// tag_directives_start *yaml_tag_directive_t, +// tag_directives_end *yaml_tag_directive_t, +// start_implicit int, end_implicit int) +//{ +// struct { +// error yaml_error_type_t +// } context +// struct { +// start *yaml_node_t +// end *yaml_node_t +// top *yaml_node_t +// } nodes = { NULL, NULL, NULL } +// version_directive_copy *yaml_version_directive_t = NULL +// struct { +// start *yaml_tag_directive_t +// end *yaml_tag_directive_t +// top *yaml_tag_directive_t +// } tag_directives_copy = { NULL, NULL, NULL } +// value yaml_tag_directive_t = { NULL, NULL } +// mark yaml_mark_t = { 0, 0, 0 } +// +// assert(document) // Non-NULL document object is expected. +// assert((tag_directives_start && tag_directives_end) || +// (tag_directives_start == tag_directives_end)) +// // Valid tag directives are expected. +// +// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error +// +// if (version_directive) { +// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) +// if (!version_directive_copy) goto error +// version_directive_copy.major = version_directive.major +// version_directive_copy.minor = version_directive.minor +// } +// +// if (tag_directives_start != tag_directives_end) { +// tag_directive *yaml_tag_directive_t +// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) +// goto error +// for (tag_directive = tag_directives_start +// tag_directive != tag_directives_end; tag_directive ++) { +// assert(tag_directive.handle) +// assert(tag_directive.prefix) +// if (!yaml_check_utf8(tag_directive.handle, +// strlen((char *)tag_directive.handle))) +// goto error +// if (!yaml_check_utf8(tag_directive.prefix, +// strlen((char *)tag_directive.prefix))) +// goto error +// value.handle = yaml_strdup(tag_directive.handle) +// value.prefix = yaml_strdup(tag_directive.prefix) +// if (!value.handle || !value.prefix) goto error +// if (!PUSH(&context, tag_directives_copy, value)) +// goto error +// value.handle = NULL +// value.prefix = NULL +// } +// } +// +// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, +// tag_directives_copy.start, tag_directives_copy.top, +// start_implicit, end_implicit, mark, mark) +// +// return 1 +// +//error: +// STACK_DEL(&context, nodes) +// yaml_free(version_directive_copy) +// while (!STACK_EMPTY(&context, tag_directives_copy)) { +// value yaml_tag_directive_t = POP(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// } +// STACK_DEL(&context, tag_directives_copy) +// yaml_free(value.handle) +// yaml_free(value.prefix) +// +// return 0 +//} +// +///* +// * Destroy a document object. +// */ +// +//YAML_DECLARE(void) +//yaml_document_delete(document *yaml_document_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// tag_directive *yaml_tag_directive_t +// +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. +// +// assert(document) // Non-NULL document object is expected. +// +// while (!STACK_EMPTY(&context, document.nodes)) { +// node yaml_node_t = POP(&context, document.nodes) +// yaml_free(node.tag) +// switch (node.type) { +// case YAML_SCALAR_NODE: +// yaml_free(node.data.scalar.value) +// break +// case YAML_SEQUENCE_NODE: +// STACK_DEL(&context, node.data.sequence.items) +// break +// case YAML_MAPPING_NODE: +// STACK_DEL(&context, node.data.mapping.pairs) +// break +// default: +// assert(0) // Should not happen. +// } +// } +// STACK_DEL(&context, document.nodes) +// +// yaml_free(document.version_directive) +// for (tag_directive = document.tag_directives.start +// tag_directive != document.tag_directives.end +// tag_directive++) { +// yaml_free(tag_directive.handle) +// yaml_free(tag_directive.prefix) +// } +// yaml_free(document.tag_directives.start) +// +// memset(document, 0, sizeof(yaml_document_t)) +//} +// +///** +// * Get a document node. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_node(document *yaml_document_t, index int) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (index > 0 && document.nodes.start + index <= document.nodes.top) { +// return document.nodes.start + index - 1 +// } +// return NULL +//} +// +///** +// * Get the root object. +// */ +// +//YAML_DECLARE(yaml_node_t *) +//yaml_document_get_root_node(document *yaml_document_t) +//{ +// assert(document) // Non-NULL document object is expected. +// +// if (document.nodes.top != document.nodes.start) { +// return document.nodes.start +// } +// return NULL +//} +// +///* +// * Add a scalar node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_scalar(document *yaml_document_t, +// tag *yaml_char_t, value *yaml_char_t, length int, +// style yaml_scalar_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// value_copy *yaml_char_t = NULL +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// assert(value) // Non-NULL value is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (length < 0) { +// length = strlen((char *)value) +// } +// +// if (!yaml_check_utf8(value, length)) goto error +// value_copy = yaml_malloc(length+1) +// if (!value_copy) goto error +// memcpy(value_copy, value, length) +// value_copy[length] = '\0' +// +// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// yaml_free(tag_copy) +// yaml_free(value_copy) +// +// return 0 +//} +// +///* +// * Add a sequence node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_sequence(document *yaml_document_t, +// tag *yaml_char_t, style yaml_sequence_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_item_t +// end *yaml_node_item_t +// top *yaml_node_item_t +// } items = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error +// +// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, items) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Add a mapping node to a document. +// */ +// +//YAML_DECLARE(int) +//yaml_document_add_mapping(document *yaml_document_t, +// tag *yaml_char_t, style yaml_mapping_style_t) +//{ +// struct { +// error yaml_error_type_t +// } context +// mark yaml_mark_t = { 0, 0, 0 } +// tag_copy *yaml_char_t = NULL +// struct { +// start *yaml_node_pair_t +// end *yaml_node_pair_t +// top *yaml_node_pair_t +// } pairs = { NULL, NULL, NULL } +// node yaml_node_t +// +// assert(document) // Non-NULL document object is expected. +// +// if (!tag) { +// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG +// } +// +// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error +// tag_copy = yaml_strdup(tag) +// if (!tag_copy) goto error +// +// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error +// +// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, +// style, mark, mark) +// if (!PUSH(&context, document.nodes, node)) goto error +// +// return document.nodes.top - document.nodes.start +// +//error: +// STACK_DEL(&context, pairs) +// yaml_free(tag_copy) +// +// return 0 +//} +// +///* +// * Append an item to a sequence node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_sequence_item(document *yaml_document_t, +// sequence int, item int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// assert(document) // Non-NULL document is required. +// assert(sequence > 0 +// && document.nodes.start + sequence <= document.nodes.top) +// // Valid sequence id is required. +// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) +// // A sequence node is required. +// assert(item > 0 && document.nodes.start + item <= document.nodes.top) +// // Valid item id is required. +// +// if (!PUSH(&context, +// document.nodes.start[sequence-1].data.sequence.items, item)) +// return 0 +// +// return 1 +//} +// +///* +// * Append a pair of a key and a value to a mapping node. +// */ +// +//YAML_DECLARE(int) +//yaml_document_append_mapping_pair(document *yaml_document_t, +// mapping int, key int, value int) +//{ +// struct { +// error yaml_error_type_t +// } context +// +// pair yaml_node_pair_t +// +// assert(document) // Non-NULL document is required. +// assert(mapping > 0 +// && document.nodes.start + mapping <= document.nodes.top) +// // Valid mapping id is required. +// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) +// // A mapping node is required. +// assert(key > 0 && document.nodes.start + key <= document.nodes.top) +// // Valid key id is required. +// assert(value > 0 && document.nodes.start + value <= document.nodes.top) +// // Valid value id is required. +// +// pair.key = key +// pair.value = value +// +// if (!PUSH(&context, +// document.nodes.start[mapping-1].data.mapping.pairs, pair)) +// return 0 +// +// return 1 +//} +// +// diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/decode.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/decode.go new file mode 100644 index 0000000000..129bc2a97d --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/decode.go @@ -0,0 +1,815 @@ +package yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +const ( + documentNode = 1 << iota + mappingNode + sequenceNode + scalarNode + aliasNode +) + +type node struct { + kind int + line, column int + tag string + // For an alias node, alias holds the resolved alias. + alias *node + value string + implicit bool + children []*node + anchors map[string]*node +} + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *node + doneInit bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *node, anchor []byte) { + if anchor != nil { + p.doc.anchors[string(anchor)] = n + } +} + +func (p *parser) parse() *node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + default: + panic("attempted to parse unknown event: " + p.event.typ.String()) + } +} + +func (p *parser) node(kind int) *node { + return &node{ + kind: kind, + line: p.event.start_mark.line, + column: p.event.start_mark.column, + } +} + +func (p *parser) document() *node { + n := p.node(documentNode) + n.anchors = make(map[string]*node) + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + n.children = append(n.children, p.parse()) + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *node { + n := p.node(aliasNode) + n.value = string(p.event.anchor) + n.alias = p.doc.anchors[n.value] + if n.alias == nil { + failf("unknown anchor '%s' referenced", n.value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *node { + n := p.node(scalarNode) + n.value = string(p.event.value) + n.tag = string(p.event.tag) + n.implicit = p.event.implicit + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *node { + n := p.node(sequenceNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + n.children = append(n.children, p.parse()) + } + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *node { + n := p.node(mappingNode) + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + n.children = append(n.children, p.parse(), p.parse()) + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *node + aliases map[*node]bool + mapType reflect.Type + terrors []string + strict bool + + decodeCount int + aliasCount int + aliasDepth int +} + +var ( + mapItemType = reflect.TypeOf(MapItem{}) + durationType = reflect.TypeOf(time.Duration(0)) + defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = defaultMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder(strict bool) *decoder { + d := &decoder{mapType: defaultMapType, strict: strict} + d.aliases = make(map[*node]bool) + return d +} + +func (d *decoder) terror(n *node, tag string, out reflect.Value) { + if n.tag != "" { + tag = n.tag + } + value := n.value + if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + if u, ok := out.Addr().Interface().(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 + + // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) +) + +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } +} + +func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + switch n.kind { + case documentNode: + return d.document(n, out) + case aliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.kind { + case scalarNode: + good = d.scalar(n, out) + case mappingNode: + good = d.mapping(n, out) + case sequenceNode: + good = d.sequence(n, out) + default: + panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) + } + return good +} + +func (d *decoder) document(n *node, out reflect.Value) (good bool) { + if len(n.children) == 1 { + d.doc = n + d.unmarshal(n.children[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) scalar(n *node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.tag == "" && !n.implicit { + tag = yaml_STR_TAG + resolved = n.value + } else { + tag, resolved = resolve(n.tag, n.value) + if tag == yaml_BINARY_TAG { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + if out.Kind() == reflect.Map && !out.CanAddr() { + resetMap(out) + } else { + out.Set(reflect.Zero(out.Type())) + } + return true + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == yaml_BINARY_TAG { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == yaml_BINARY_TAG { + out.SetString(resolved.(string)) + return true + } + if resolved != nil { + out.SetString(n.value) + return true + } + case reflect.Interface: + if resolved == nil { + out.Set(reflect.Zero(out.Type())) + } else if tag == yaml_TIMESTAMP_TAG { + // It looks like a timestamp but for backward compatibility + // reasons we set it as a string, so that code that unmarshals + // timestamp-like values into interface{} will continue to + // see a string and not a time.Time. + // TODO(v3) Drop this. + out.Set(reflect.ValueOf(n.value)) + } else { + out.Set(reflect.ValueOf(resolved)) + } + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + switch resolved := resolved.(type) { + case int: + if !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + if out.Type().Elem() == reflect.TypeOf(resolved) { + // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? + elem := reflect.New(out.Type().Elem()) + elem.Elem().Set(reflect.ValueOf(resolved)) + out.Set(elem) + return true + } + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { + l := len(n.children) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, yaml_SEQ_TAG, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.children[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Slice: + return d.mappingSlice(n, out) + case reflect.Map: + // okay + case reflect.Interface: + if d.mapType.Kind() == reflect.Map { + iface := out + out = reflect.MakeMap(d.mapType) + iface.Set(out) + } else { + slicev := reflect.New(d.mapType).Elem() + if !d.mappingSlice(n, slicev) { + return false + } + out.Set(slicev) + return true + } + default: + d.terror(n, yaml_MAP_TAG, out) + return false + } + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + mapType := d.mapType + if outt.Key() == ifaceType && outt.Elem() == ifaceType { + d.mapType = outt + } + + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + } + l := len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.children[i], k) { + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.children[i+1], e) { + d.setMapIndex(n.children[i+1], out, k, e) + } + } + } + d.mapType = mapType + return true +} + +func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { + if d.strict && out.MapIndex(k) != zeroValue { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) + return + } + out.SetMapIndex(k, v) +} + +func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { + outt := out.Type() + if outt.Elem() != mapItemType { + d.terror(n, yaml_MAP_TAG, out) + return false + } + + mapType := d.mapType + d.mapType = outt + + var slice []MapItem + var l = len(n.children) + for i := 0; i < l; i += 2 { + if isMerge(n.children[i]) { + d.merge(n.children[i+1], out) + continue + } + item := MapItem{} + k := reflect.ValueOf(&item.Key).Elem() + if d.unmarshal(n.children[i], k) { + v := reflect.ValueOf(&item.Value).Elem() + if d.unmarshal(n.children[i+1], v) { + slice = append(slice, item) + } + } + } + out.Set(reflect.ValueOf(slice)) + d.mapType = mapType + return true +} + +func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + name := settableValueOf("") + l := len(n.children) + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) + elemType = inlineMap.Type().Elem() + } + + var doneFields []bool + if d.strict { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + for i := 0; i < l; i += 2 { + ni := n.children[i] + if isMerge(ni) { + d.merge(n.children[i+1], out) + continue + } + if !d.unmarshal(ni, name) { + continue + } + if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.strict { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = out.FieldByIndex(info.Inline) + } + d.unmarshal(n.children[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.children[i+1], value) + d.setMapIndex(n.children[i+1], inlineMap, name, value) + } else if d.strict { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) + } + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) merge(n *node, out reflect.Value) { + switch n.kind { + case mappingNode: + d.unmarshal(n, out) + case aliasNode: + if n.alias != nil && n.alias.kind != mappingNode { + failWantMap() + } + d.unmarshal(n, out) + case sequenceNode: + // Step backwards as earlier nodes take precedence. + for i := len(n.children) - 1; i >= 0; i-- { + ni := n.children[i] + if ni.kind == aliasNode { + if ni.alias != nil && ni.alias.kind != mappingNode { + failWantMap() + } + } else if ni.kind != mappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } +} + +func isMerge(n *node) bool { + return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/emitterc.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/emitterc.go new file mode 100644 index 0000000000..a1c2cc5262 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/emitterc.go @@ -0,0 +1,1685 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Flush the buffer if needed. +func flush(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) { + return yaml_emitter_flush(emitter) + } + return true +} + +// Put a character to the output buffer. +func put(emitter *yaml_emitter_t, value byte) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + emitter.buffer[emitter.buffer_pos] = value + emitter.buffer_pos++ + emitter.column++ + return true +} + +// Put a line break to the output buffer. +func put_break(emitter *yaml_emitter_t) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + switch emitter.line_break { + case yaml_CR_BREAK: + emitter.buffer[emitter.buffer_pos] = '\r' + emitter.buffer_pos += 1 + case yaml_LN_BREAK: + emitter.buffer[emitter.buffer_pos] = '\n' + emitter.buffer_pos += 1 + case yaml_CRLN_BREAK: + emitter.buffer[emitter.buffer_pos+0] = '\r' + emitter.buffer[emitter.buffer_pos+1] = '\n' + emitter.buffer_pos += 2 + default: + panic("unknown line break setting") + } + emitter.column = 0 + emitter.line++ + return true +} + +// Copy a character from a string into buffer. +func write(emitter *yaml_emitter_t, s []byte, i *int) bool { + if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { + return false + } + p := emitter.buffer_pos + w := width(s[*i]) + switch w { + case 4: + emitter.buffer[p+3] = s[*i+3] + fallthrough + case 3: + emitter.buffer[p+2] = s[*i+2] + fallthrough + case 2: + emitter.buffer[p+1] = s[*i+1] + fallthrough + case 1: + emitter.buffer[p+0] = s[*i+0] + default: + panic("unknown character width") + } + emitter.column++ + emitter.buffer_pos += w + *i += w + return true +} + +// Write a whole string into buffer. +func write_all(emitter *yaml_emitter_t, s []byte) bool { + for i := 0; i < len(s); { + if !write(emitter, s, &i) { + return false + } + } + return true +} + +// Copy a line break character from a string into buffer. +func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { + if s[*i] == '\n' { + if !put_break(emitter) { + return false + } + *i++ + } else { + if !write(emitter, s, i) { + return false + } + emitter.column = 0 + emitter.line++ + } + return true +} + +// Set an emitter error and return false. +func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_EMITTER_ERROR + emitter.problem = problem + return false +} + +// Emit an event. +func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.events = append(emitter.events, *event) + for !yaml_emitter_need_more_events(emitter) { + event := &emitter.events[emitter.events_head] + if !yaml_emitter_analyze_event(emitter, event) { + return false + } + if !yaml_emitter_state_machine(emitter, event) { + return false + } + yaml_event_delete(event) + emitter.events_head++ + } + return true +} + +// Check if we need to accumulate more events before emitting. +// +// We accumulate extra +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// +func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { + if emitter.events_head == len(emitter.events) { + return true + } + var accumulate int + switch emitter.events[emitter.events_head].typ { + case yaml_DOCUMENT_START_EVENT: + accumulate = 1 + break + case yaml_SEQUENCE_START_EVENT: + accumulate = 2 + break + case yaml_MAPPING_START_EVENT: + accumulate = 3 + break + default: + return false + } + if len(emitter.events)-emitter.events_head > accumulate { + return false + } + var level int + for i := emitter.events_head; i < len(emitter.events); i++ { + switch emitter.events[i].typ { + case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: + level++ + case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: + level-- + } + if level == 0 { + return false + } + } + return true +} + +// Append a directive to the directives stack. +func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { + for i := 0; i < len(emitter.tag_directives); i++ { + if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") + } + } + + // [Go] Do we actually need to copy this given garbage collection + // and the lack of deallocating destructors? + tag_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(tag_copy.handle, value.handle) + copy(tag_copy.prefix, value.prefix) + emitter.tag_directives = append(emitter.tag_directives, tag_copy) + return true +} + +// Increase the indentation level. +func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { + emitter.indents = append(emitter.indents, emitter.indent) + if emitter.indent < 0 { + if flow { + emitter.indent = emitter.best_indent + } else { + emitter.indent = 0 + } + } else if !indentless { + emitter.indent += emitter.best_indent + } + return true +} + +// State dispatcher. +func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { + switch emitter.state { + default: + case yaml_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event) + + case yaml_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, true) + + case yaml_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, false) + + case yaml_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event) + + case yaml_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event) + + case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, true) + + case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false) + + case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, true) + + case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, false) + + case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, true) + + case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, false) + + case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, true) + + case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, false) + + case yaml_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") + } + panic("invalid emitter state") +} + +// Expect STREAM-START. +func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_STREAM_START_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") + } + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = event.encoding + if emitter.encoding == yaml_ANY_ENCODING { + emitter.encoding = yaml_UTF8_ENCODING + } + } + if emitter.best_indent < 2 || emitter.best_indent > 9 { + emitter.best_indent = 2 + } + if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { + emitter.best_width = 80 + } + if emitter.best_width < 0 { + emitter.best_width = 1<<31 - 1 + } + if emitter.line_break == yaml_ANY_BREAK { + emitter.line_break = yaml_LN_BREAK + } + + emitter.indent = -1 + emitter.line = 0 + emitter.column = 0 + emitter.whitespace = true + emitter.indention = true + + if emitter.encoding != yaml_UTF8_ENCODING { + if !yaml_emitter_write_bom(emitter) { + return false + } + } + emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE + return true +} + +// Expect DOCUMENT-START or STREAM-END. +func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + + if event.typ == yaml_DOCUMENT_START_EVENT { + + if event.version_directive != nil { + if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { + return false + } + } + + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { + return false + } + if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { + return false + } + } + + for i := 0; i < len(default_tag_directives); i++ { + tag_directive := &default_tag_directives[i] + if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { + return false + } + } + + implicit := event.implicit + if !first || emitter.canonical { + implicit = false + } + + if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if event.version_directive != nil { + implicit = false + if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if len(event.tag_directives) > 0 { + implicit = false + for i := 0; i < len(event.tag_directives); i++ { + tag_directive := &event.tag_directives[i] + if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { + return false + } + if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + if yaml_emitter_check_empty_document(emitter) { + implicit = false + } + if !implicit { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { + return false + } + if emitter.canonical { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + } + + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE + return true + } + + if event.typ == yaml_STREAM_END_EVENT { + if emitter.open_ended { + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_END_STATE + return true + } + + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") +} + +// Expect the root node. +func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { + emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) + return yaml_emitter_emit_node(emitter, event, true, false, false, false) +} + +// Expect DOCUMENT-END. +func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if event.typ != yaml_DOCUMENT_END_EVENT { + return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !event.implicit { + // [Go] Allocate the slice elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_flush(emitter) { + return false + } + emitter.state = yaml_EMIT_DOCUMENT_START_STATE + emitter.tag_directives = emitter.tag_directives[:0] + return true +} + +// Expect a flow item node. +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a flow key node. +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + emitter.flow_level++ + } + + if event.typ == yaml_MAPPING_END_EVENT { + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.canonical && !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + + if !first { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + + if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a flow value node. +func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if emitter.canonical || emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block item node. +func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { + return false + } + } + if event.typ == yaml_SEQUENCE_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) + return yaml_emitter_emit_node(emitter, event, false, true, false, false) +} + +// Expect a block key node. +func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { + if first { + if !yaml_emitter_increase_indent(emitter, false, false) { + return false + } + } + if event.typ == yaml_MAPPING_END_EVENT { + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if yaml_emitter_check_simple_key(emitter) { + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, true) + } + if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { + return false + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a block value node. +func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { + if simple { + if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { + return false + } + } else { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { + return false + } + } + emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) + return yaml_emitter_emit_node(emitter, event, false, false, true, false) +} + +// Expect a node. +func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, + root bool, sequence bool, mapping bool, simple_key bool) bool { + + emitter.root_context = root + emitter.sequence_context = sequence + emitter.mapping_context = mapping + emitter.simple_key_context = simple_key + + switch event.typ { + case yaml_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event) + case yaml_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event) + case yaml_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event) + case yaml_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event) + default: + return yaml_emitter_set_emitter_error(emitter, + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) + } +} + +// Expect ALIAS. +func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SCALAR. +func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_select_scalar_style(emitter, event) { + return false + } + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if !yaml_emitter_increase_indent(emitter, true, false) { + return false + } + if !yaml_emitter_process_scalar(emitter) { + return false + } + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + emitter.state = emitter.states[len(emitter.states)-1] + emitter.states = emitter.states[:len(emitter.states)-1] + return true +} + +// Expect SEQUENCE-START. +func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || + yaml_emitter_check_empty_sequence(emitter) { + emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE + } + return true +} + +// Expect MAPPING-START. +func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { + if !yaml_emitter_process_anchor(emitter) { + return false + } + if !yaml_emitter_process_tag(emitter) { + return false + } + if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || + yaml_emitter_check_empty_mapping(emitter) { + emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE + } else { + emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE + } + return true +} + +// Check if the document content is an empty scalar. +func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { + return false // [Go] Huh? +} + +// Check if the next events represent an empty sequence. +func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT +} + +// Check if the next events represent an empty mapping. +func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { + if len(emitter.events)-emitter.events_head < 2 { + return false + } + return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && + emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT +} + +// Check if the next node can be expressed as a simple key. +func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { + length := 0 + switch emitter.events[emitter.events_head].typ { + case yaml_ALIAS_EVENT: + length += len(emitter.anchor_data.anchor) + case yaml_SCALAR_EVENT: + if emitter.scalar_data.multiline { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + + len(emitter.scalar_data.value) + case yaml_SEQUENCE_START_EVENT: + if !yaml_emitter_check_empty_sequence(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + case yaml_MAPPING_START_EVENT: + if !yaml_emitter_check_empty_mapping(emitter) { + return false + } + length += len(emitter.anchor_data.anchor) + + len(emitter.tag_data.handle) + + len(emitter.tag_data.suffix) + default: + return false + } + return length <= 128 +} + +// Determine an acceptable scalar style. +func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 + if no_tag && !event.implicit && !event.quoted_implicit { + return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") + } + + style := event.scalar_style() + if style == yaml_ANY_SCALAR_STYLE { + style = yaml_PLAIN_SCALAR_STYLE + } + if emitter.canonical { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + if emitter.simple_key_context && emitter.scalar_data.multiline { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + if style == yaml_PLAIN_SCALAR_STYLE { + if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || + emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + if no_tag && !event.implicit { + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { + if !emitter.scalar_data.single_quoted_allowed { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { + if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + } + + if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { + emitter.tag_data.handle = []byte{'!'} + } + emitter.scalar_data.style = style + return true +} + +// Write an anchor. +func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { + if emitter.anchor_data.anchor == nil { + return true + } + c := []byte{'&'} + if emitter.anchor_data.alias { + c[0] = '*' + } + if !yaml_emitter_write_indicator(emitter, c, true, false, false) { + return false + } + return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) +} + +// Write a tag. +func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { + if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { + return true + } + if len(emitter.tag_data.handle) > 0 { + if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { + return false + } + if len(emitter.tag_data.suffix) > 0 { + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + } + } else { + // [Go] Allocate these slices elsewhere. + if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { + return false + } + if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { + return false + } + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { + return false + } + } + return true +} + +// Write a scalar. +func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { + switch emitter.scalar_data.style { + case yaml_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) + + case yaml_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) + + case yaml_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) + } + panic("unknown scalar style") +} + +// Check if a %YAML directive is valid. +func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { + if version_directive.major != 1 || version_directive.minor != 1 { + return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") + } + return true +} + +// Check if a %TAG directive is valid. +func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { + handle := tag_directive.handle + prefix := tag_directive.prefix + if len(handle) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") + } + if handle[0] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") + } + if handle[len(handle)-1] != '!' { + return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") + } + for i := 1; i < len(handle)-1; i += width(handle[i]) { + if !is_alpha(handle, i) { + return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") + } + } + if len(prefix) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") + } + return true +} + +// Check if an anchor is valid. +func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { + if len(anchor) == 0 { + problem := "anchor value must not be empty" + if alias { + problem = "alias value must not be empty" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + for i := 0; i < len(anchor); i += width(anchor[i]) { + if !is_alpha(anchor, i) { + problem := "anchor value must contain alphanumerical characters only" + if alias { + problem = "alias value must contain alphanumerical characters only" + } + return yaml_emitter_set_emitter_error(emitter, problem) + } + } + emitter.anchor_data.anchor = anchor + emitter.anchor_data.alias = alias + return true +} + +// Check if a tag is valid. +func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { + if len(tag) == 0 { + return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") + } + for i := 0; i < len(emitter.tag_directives); i++ { + tag_directive := &emitter.tag_directives[i] + if bytes.HasPrefix(tag, tag_directive.prefix) { + emitter.tag_data.handle = tag_directive.handle + emitter.tag_data.suffix = tag[len(tag_directive.prefix):] + return true + } + } + emitter.tag_data.suffix = tag + return true +} + +// Check if a scalar is valid. +func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { + var ( + block_indicators = false + flow_indicators = false + line_breaks = false + special_characters = false + + leading_space = false + leading_break = false + trailing_space = false + trailing_break = false + break_space = false + space_break = false + + preceded_by_whitespace = false + followed_by_whitespace = false + previous_space = false + previous_break = false + ) + + emitter.scalar_data.value = value + + if len(value) == 0 { + emitter.scalar_data.multiline = false + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = false + return true + } + + if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { + block_indicators = true + flow_indicators = true + } + + preceded_by_whitespace = true + for i, w := 0, 0; i < len(value); i += w { + w = width(value[i]) + followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) + + if i == 0 { + switch value[i] { + case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': + flow_indicators = true + block_indicators = true + case '?', ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '-': + if followed_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } else { + switch value[i] { + case ',', '?', '[', ']', '{', '}': + flow_indicators = true + case ':': + flow_indicators = true + if followed_by_whitespace { + block_indicators = true + } + case '#': + if preceded_by_whitespace { + flow_indicators = true + block_indicators = true + } + } + } + + if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + special_characters = true + } + if is_space(value, i) { + if i == 0 { + leading_space = true + } + if i+width(value[i]) == len(value) { + trailing_space = true + } + if previous_break { + break_space = true + } + previous_space = true + previous_break = false + } else if is_break(value, i) { + line_breaks = true + if i == 0 { + leading_break = true + } + if i+width(value[i]) == len(value) { + trailing_break = true + } + if previous_space { + space_break = true + } + previous_space = false + previous_break = true + } else { + previous_space = false + previous_break = false + } + + // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. + preceded_by_whitespace = is_blankz(value, i) + } + + emitter.scalar_data.multiline = line_breaks + emitter.scalar_data.flow_plain_allowed = true + emitter.scalar_data.block_plain_allowed = true + emitter.scalar_data.single_quoted_allowed = true + emitter.scalar_data.block_allowed = true + + if leading_space || leading_break || trailing_space || trailing_break { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if trailing_space { + emitter.scalar_data.block_allowed = false + } + if break_space { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + emitter.scalar_data.single_quoted_allowed = false + emitter.scalar_data.block_allowed = false + } + if line_breaks { + emitter.scalar_data.flow_plain_allowed = false + emitter.scalar_data.block_plain_allowed = false + } + if flow_indicators { + emitter.scalar_data.flow_plain_allowed = false + } + if block_indicators { + emitter.scalar_data.block_plain_allowed = false + } + return true +} + +// Check if the event data is valid. +func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { + + emitter.anchor_data.anchor = nil + emitter.tag_data.handle = nil + emitter.tag_data.suffix = nil + emitter.scalar_data.value = nil + + switch event.typ { + case yaml_ALIAS_EVENT: + if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { + return false + } + + case yaml_SCALAR_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + if !yaml_emitter_analyze_scalar(emitter, event.value) { + return false + } + + case yaml_SEQUENCE_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + + case yaml_MAPPING_START_EVENT: + if len(event.anchor) > 0 { + if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { + return false + } + } + if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { + if !yaml_emitter_analyze_tag(emitter, event.tag) { + return false + } + } + } + return true +} + +// Write the BOM character. +func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { + if !flush(emitter) { + return false + } + pos := emitter.buffer_pos + emitter.buffer[pos+0] = '\xEF' + emitter.buffer[pos+1] = '\xBB' + emitter.buffer[pos+2] = '\xBF' + emitter.buffer_pos += 3 + return true +} + +func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { + indent := emitter.indent + if indent < 0 { + indent = 0 + } + if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { + if !put_break(emitter) { + return false + } + } + for emitter.column < indent { + if !put(emitter, ' ') { + return false + } + } + emitter.whitespace = true + emitter.indention = true + return true +} + +func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, indicator) { + return false + } + emitter.whitespace = is_whitespace + emitter.indention = (emitter.indention && is_indention) + emitter.open_ended = false + return true +} + +func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !write_all(emitter, value) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { + if need_whitespace && !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + for i := 0; i < len(value); { + var must_write bool + switch value[i] { + case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': + must_write = true + default: + must_write = is_alpha(value, i) + } + if must_write { + if !write(emitter, value, &i) { + return false + } + } else { + w := width(value[i]) + for k := 0; k < w; k++ { + octet := value[i] + i++ + if !put(emitter, '%') { + return false + } + + c := octet >> 4 + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + + c = octet & 0x0f + if c < 10 { + c += '0' + } else { + c += 'A' - 10 + } + if !put(emitter, c) { + return false + } + } + } + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + + emitter.whitespace = false + emitter.indention = false + if emitter.root_context { + emitter.open_ended = true + } + + return true +} + +func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { + return false + } + + spaces := false + breaks := false + for i := 0; i < len(value); { + if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + spaces = true + } else if is_break(value, i) { + if !breaks && value[i] == '\n' { + if !put_break(emitter) { + return false + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if value[i] == '\'' { + if !put(emitter, '\'') { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + spaces = false + breaks = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { + spaces := false + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { + return false + } + + for i := 0; i < len(value); { + if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || + is_bom(value, i) || is_break(value, i) || + value[i] == '"' || value[i] == '\\' { + + octet := value[i] + + var w int + var v rune + switch { + case octet&0x80 == 0x00: + w, v = 1, rune(octet&0x7F) + case octet&0xE0 == 0xC0: + w, v = 2, rune(octet&0x1F) + case octet&0xF0 == 0xE0: + w, v = 3, rune(octet&0x0F) + case octet&0xF8 == 0xF0: + w, v = 4, rune(octet&0x07) + } + for k := 1; k < w; k++ { + octet = value[i+k] + v = (v << 6) + (rune(octet) & 0x3F) + } + i += w + + if !put(emitter, '\\') { + return false + } + + var ok bool + switch v { + case 0x00: + ok = put(emitter, '0') + case 0x07: + ok = put(emitter, 'a') + case 0x08: + ok = put(emitter, 'b') + case 0x09: + ok = put(emitter, 't') + case 0x0A: + ok = put(emitter, 'n') + case 0x0b: + ok = put(emitter, 'v') + case 0x0c: + ok = put(emitter, 'f') + case 0x0d: + ok = put(emitter, 'r') + case 0x1b: + ok = put(emitter, 'e') + case 0x22: + ok = put(emitter, '"') + case 0x5c: + ok = put(emitter, '\\') + case 0x85: + ok = put(emitter, 'N') + case 0xA0: + ok = put(emitter, '_') + case 0x2028: + ok = put(emitter, 'L') + case 0x2029: + ok = put(emitter, 'P') + default: + if v <= 0xFF { + ok = put(emitter, 'x') + w = 2 + } else if v <= 0xFFFF { + ok = put(emitter, 'u') + w = 4 + } else { + ok = put(emitter, 'U') + w = 8 + } + for k := (w - 1) * 4; ok && k >= 0; k -= 4 { + digit := byte((v >> uint(k)) & 0x0F) + if digit < 10 { + ok = put(emitter, digit+'0') + } else { + ok = put(emitter, digit+'A'-10) + } + } + } + if !ok { + return false + } + spaces = false + } else if is_space(value, i) { + if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if is_space(value, i+1) { + if !put(emitter, '\\') { + return false + } + } + i += width(value[i]) + } else if !write(emitter, value, &i) { + return false + } + spaces = true + } else { + if !write(emitter, value, &i) { + return false + } + spaces = false + } + } + if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { + return false + } + emitter.whitespace = false + emitter.indention = false + return true +} + +func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { + if is_space(value, 0) || is_break(value, 0) { + indent_hint := []byte{'0' + byte(emitter.best_indent)} + if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { + return false + } + } + + emitter.open_ended = false + + var chomp_hint [1]byte + if len(value) == 0 { + chomp_hint[0] = '-' + } else { + i := len(value) - 1 + for value[i]&0xC0 == 0x80 { + i-- + } + if !is_break(value, i) { + chomp_hint[0] = '-' + } else if i == 0 { + chomp_hint[0] = '+' + emitter.open_ended = true + } else { + i-- + for value[i]&0xC0 == 0x80 { + i-- + } + if is_break(value, i) { + chomp_hint[0] = '+' + emitter.open_ended = true + } + } + } + if chomp_hint[0] != 0 { + if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { + return false + } + } + return true +} + +func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + breaks := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if !write(emitter, value, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + + return true +} + +func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { + if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { + return false + } + if !yaml_emitter_write_block_scalar_hints(emitter, value) { + return false + } + + if !put_break(emitter) { + return false + } + emitter.indention = true + emitter.whitespace = true + + breaks := true + leading_spaces := true + for i := 0; i < len(value); { + if is_break(value, i) { + if !breaks && !leading_spaces && value[i] == '\n' { + k := 0 + for is_break(value, k) { + k += width(value[k]) + } + if !is_blankz(value, k) { + if !put_break(emitter) { + return false + } + } + } + if !write_break(emitter, value, &i) { + return false + } + emitter.indention = true + breaks = true + } else { + if breaks { + if !yaml_emitter_write_indent(emitter) { + return false + } + leading_spaces = is_blank(value, i) + } + if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { + if !yaml_emitter_write_indent(emitter) { + return false + } + i += width(value[i]) + } else { + if !write(emitter, value, &i) { + return false + } + } + emitter.indention = false + breaks = false + } + } + return true +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/encode.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/encode.go new file mode 100644 index 0000000000..0ee738e11b --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/encode.go @@ -0,0 +1,390 @@ +package yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// jsonNumber is the interface of the encoding/json.Number datatype. +// Repeating the interface here avoids a dependency on encoding/json, and also +// supports other libraries like jsoniter, which use a similar datatype with +// the same interface. Detecting this interface is useful when dealing with +// structures containing json.Number, which is a string under the hood. The +// encoder should prefer the use of Int64(), Float64() and string(), in that +// order, when encoding this type. +type jsonNumber interface { + Float64() (float64, error) + Int64() (int64, error) + String() string +} + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + // doneInit holds whether the initial stream_start_event has been + // emitted. + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch m := iface.(type) { + case jsonNumber: + integer, err := m.Int64() + if err == nil { + // In this case the json.Number is a valid int64 + in = reflect.ValueOf(integer) + break + } + float, err := m.Float64() + if err == nil { + // In this case the json.Number is a valid float64 + in = reflect.ValueOf(float) + break + } + // fallback case - no number could be obtained + in = reflect.ValueOf(m.String()) + case time.Time, *time.Time: + // Although time.Time implements TextMarshaler, + // we don't want to treat it as a string for YAML + // purposes because YAML has special support for + // timestamps. + case Marshaler: + v, err := m.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + in = reflect.ValueOf(v) + case encoding.TextMarshaler: + text, err := m.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + if in.Type() == ptrTimeType { + e.timev(tag, in.Elem()) + } else { + e.marshal(tag, in.Elem()) + } + case reflect.Struct: + if in.Type() == timeType { + e.timev(tag, in) + } else { + e.structv(tag, in) + } + case reflect.Slice, reflect.Array: + if in.Type().Elem() == mapItemType { + e.itemsv(tag, in) + } else { + e.slicev(tag, in) + } + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if in.Type() == durationType { + e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) + } else { + e.intv(tag, in) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) itemsv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) + for _, item := range slice { + e.marshal("", reflect.ValueOf(item.Key)) + e.marshal("", reflect.ValueOf(item.Value)) + } + }) +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = in.FieldByIndex(info.Inline) + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == yaml_BINARY_TAG { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = yaml_BINARY_TAG + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { + implicit := tag == "" + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.emit() +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/parserc.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/parserc.go new file mode 100644 index 0000000000..81d05dfe57 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/parserc.go @@ -0,0 +1,1095 @@ +package yaml + +import ( + "bytes" +) + +// The parser implements the following grammar: +// +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// implicit_document ::= block_node DOCUMENT-END* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// block_node_or_indentless_sequence ::= +// ALIAS +// | properties (block_content | indentless_block_sequence)? +// | block_content +// | indentless_block_sequence +// block_node ::= ALIAS +// | properties block_content? +// | block_content +// flow_node ::= ALIAS +// | properties flow_content? +// | flow_content +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// block_content ::= block_collection | flow_collection | SCALAR +// flow_content ::= flow_collection | SCALAR +// block_collection ::= block_sequence | block_mapping +// flow_collection ::= flow_sequence | flow_mapping +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// block_mapping ::= BLOCK-MAPPING_START +// ((KEY block_node_or_indentless_sequence?)? +// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// flow_sequence ::= FLOW-SEQUENCE-START +// (flow_sequence_entry FLOW-ENTRY)* +// flow_sequence_entry? +// FLOW-SEQUENCE-END +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// flow_mapping ::= FLOW-MAPPING-START +// (flow_mapping_entry FLOW-ENTRY)* +// flow_mapping_entry? +// FLOW-MAPPING-END +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + +// Peek the next token in the token queue. +func peek_token(parser *yaml_parser_t) *yaml_token_t { + if parser.token_available || yaml_parser_fetch_more_tokens(parser) { + return &parser.tokens[parser.tokens_head] + } + return nil +} + +// Remove the next token from the queue (must be called after peek_token). +func skip_token(parser *yaml_parser_t) { + parser.token_available = false + parser.tokens_parsed++ + parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN + parser.tokens_head++ +} + +// Get the next event. +func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { + // Erase the event object. + *event = yaml_event_t{} + + // No events after the end of the stream or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { + return true + } + + // Generate the next event. + return yaml_parser_state_machine(parser, event) +} + +// Set parser error. +func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { + parser.error = yaml_PARSER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = problem_mark + return false +} + +// State dispatcher. +func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { + //trace("yaml_parser_state_machine", "state:", parser.state.String()) + + switch parser.state { + case yaml_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event) + + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, true) + + case yaml_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, false) + + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event) + + case yaml_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event) + + case yaml_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, true, false) + + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, true, true) + + case yaml_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, false, false) + + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, true) + + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, false) + + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event) + + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, true) + + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, false) + + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, true) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, false) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) + + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) + + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, true) + + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, false) + + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, true) + + default: + panic("invalid parser state") + } +} + +// Parse the production: +// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +// ************ +func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_STREAM_START_TOKEN { + return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) + } + parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + encoding: token.encoding, + } + skip_token(parser) + return true +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// * +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// ************************* +func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { + + token := peek_token(parser) + if token == nil { + return false + } + + // Parse extra document end indicators. + if !implicit { + for token.typ == yaml_DOCUMENT_END_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && + token.typ != yaml_TAG_DIRECTIVE_TOKEN && + token.typ != yaml_DOCUMENT_START_TOKEN && + token.typ != yaml_STREAM_END_TOKEN { + // Parse an implicit document. + if !yaml_parser_process_directives(parser, nil, nil) { + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_BLOCK_NODE_STATE + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + } else if token.typ != yaml_STREAM_END_TOKEN { + // Parse an explicit document. + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + start_mark := token.start_mark + if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { + return false + } + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_DOCUMENT_START_TOKEN { + yaml_parser_set_parser_error(parser, + "did not find expected ", token.start_mark) + return false + } + parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) + parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE + end_mark := token.end_mark + + *event = yaml_event_t{ + typ: yaml_DOCUMENT_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + version_directive: version_directive, + tag_directives: tag_directives, + implicit: false, + } + skip_token(parser) + + } else { + // Parse the stream end. + parser.state = yaml_PARSE_END_STATE + *event = yaml_event_t{ + typ: yaml_STREAM_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + } + + return true +} + +// Parse the productions: +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** +// +func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || + token.typ == yaml_TAG_DIRECTIVE_TOKEN || + token.typ == yaml_DOCUMENT_START_TOKEN || + token.typ == yaml_DOCUMENT_END_TOKEN || + token.typ == yaml_STREAM_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + return yaml_parser_process_empty_scalar(parser, event, + token.start_mark) + } + return yaml_parser_parse_node(parser, event, true, false) +} + +// Parse the productions: +// implicit_document ::= block_node DOCUMENT-END* +// ************* +// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// +func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + start_mark := token.start_mark + end_mark := token.start_mark + + implicit := true + if token.typ == yaml_DOCUMENT_END_TOKEN { + end_mark = token.end_mark + skip_token(parser) + implicit = false + } + + parser.tag_directives = parser.tag_directives[:0] + + parser.state = yaml_PARSE_DOCUMENT_START_STATE + *event = yaml_event_t{ + typ: yaml_DOCUMENT_END_EVENT, + start_mark: start_mark, + end_mark: end_mark, + implicit: implicit, + } + return true +} + +// Parse the productions: +// block_node_or_indentless_sequence ::= +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * +// block_node ::= ALIAS +// ***** +// | properties block_content? +// ********** * +// | block_content +// * +// flow_node ::= ALIAS +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * +// properties ::= TAG ANCHOR? | ANCHOR TAG? +// ************************* +// block_content ::= block_collection | flow_collection | SCALAR +// ****** +// flow_content ::= flow_collection | SCALAR +// ****** +func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { + //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_ALIAS_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + anchor: token.value, + } + skip_token(parser) + return true + } + + start_mark := token.start_mark + end_mark := token.start_mark + + var tag_token bool + var tag_handle, tag_suffix, anchor []byte + var tag_mark yaml_mark_t + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + start_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } else if token.typ == yaml_TAG_TOKEN { + tag_token = true + tag_handle = token.value + tag_suffix = token.suffix + start_mark = token.start_mark + tag_mark = token.start_mark + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_ANCHOR_TOKEN { + anchor = token.value + end_mark = token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + } + + var tag []byte + if tag_token { + if len(tag_handle) == 0 { + tag = tag_suffix + tag_suffix = nil + } else { + for i := range parser.tag_directives { + if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { + tag = append([]byte(nil), parser.tag_directives[i].prefix...) + tag = append(tag, tag_suffix...) + break + } + } + if len(tag) == 0 { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark) + return false + } + } + } + + implicit := len(tag) == 0 + if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_SCALAR_TOKEN { + var plain_implicit, quoted_implicit bool + end_mark = token.end_mark + if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { + plain_implicit = true + } else if len(tag) == 0 { + quoted_implicit = true + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + value: token.value, + implicit: plain_implicit, + quoted_implicit: quoted_implicit, + style: yaml_style_t(token.style), + } + skip_token(parser) + return true + } + if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { + // [Go] Some of the events below can be merged as they differ only on style. + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), + } + return true + } + if token.typ == yaml_FLOW_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_SEQUENCE_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), + } + return true + } + if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { + end_mark = token.end_mark + parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), + } + return true + } + if len(anchor) > 0 || len(tag) > 0 { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: start_mark, + end_mark: end_mark, + anchor: anchor, + tag: tag, + implicit: implicit, + quoted_implicit: false, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true + } + + context := "while parsing a flow node" + if block { + context = "while parsing a block node" + } + yaml_parser_set_parser_error_context(parser, context, start_mark, + "did not find expected node content", token.start_mark) + return false +} + +// Parse the productions: +// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* +// +func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } else { + parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } + if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", context_mark, + "did not find expected '-' indicator", token.start_mark) +} + +// Parse the productions: +// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +// *********** * +func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_BLOCK_ENTRY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_BLOCK_ENTRY_TOKEN && + token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, true, false) + } + parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? + } + return true +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* +// +// BLOCK-END +// ********* +// +func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ == yaml_KEY_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } else { + parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + } else if token.typ == yaml_BLOCK_END_TOKEN { + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true + } + + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", context_mark, + "did not find expected key", token.start_mark) +} + +// Parse the productions: +// block_mapping ::= BLOCK-MAPPING_START +// +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// +// +func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + mark := token.end_mark + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_KEY_TOKEN && + token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_BLOCK_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, true, true) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) + } + parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence ::= FLOW-SEQUENCE-START +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", context_mark, + "did not find expected ',' or ']'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_START_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + implicit: true, + style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), + } + skip_token(parser) + return true + } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + + *event = yaml_event_t{ + typ: yaml_SEQUENCE_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + + skip_token(parser) + return true +} + +// +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + mark := token.end_mark + skip_token(parser) + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * +// +func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token := peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Parse the productions: +// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * +// +func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { + token := peek_token(parser) + if token == nil { + return false + } + parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? + } + return true +} + +// Parse the productions: +// flow_mapping ::= FLOW-MAPPING-START +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * *** * +// +func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { + if first { + token := peek_token(parser) + parser.marks = append(parser.marks, token.start_mark) + skip_token(parser) + } + + token := peek_token(parser) + if token == nil { + return false + } + + if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + if !first { + if token.typ == yaml_FLOW_ENTRY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } else { + context_mark := parser.marks[len(parser.marks)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", context_mark, + "did not find expected ',' or '}'", token.start_mark) + } + } + + if token.typ == yaml_KEY_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_VALUE_TOKEN && + token.typ != yaml_FLOW_ENTRY_TOKEN && + token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } else { + parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + + parser.state = parser.states[len(parser.states)-1] + parser.states = parser.states[:len(parser.states)-1] + parser.marks = parser.marks[:len(parser.marks)-1] + *event = yaml_event_t{ + typ: yaml_MAPPING_END_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + } + skip_token(parser) + return true +} + +// Parse the productions: +// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * ***** * +// +func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { + token := peek_token(parser) + if token == nil { + return false + } + if empty { + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) + } + if token.typ == yaml_VALUE_TOKEN { + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { + parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) + return yaml_parser_parse_node(parser, event, false, false) + } + } + parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE + return yaml_parser_process_empty_scalar(parser, event, token.start_mark) +} + +// Generate an empty scalar event. +func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { + *event = yaml_event_t{ + typ: yaml_SCALAR_EVENT, + start_mark: mark, + end_mark: mark, + value: nil, // Empty + implicit: true, + style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), + } + return true +} + +var default_tag_directives = []yaml_tag_directive_t{ + {[]byte("!"), []byte("!")}, + {[]byte("!!"), []byte("tag:yaml.org,2002:")}, +} + +// Parse directives. +func yaml_parser_process_directives(parser *yaml_parser_t, + version_directive_ref **yaml_version_directive_t, + tag_directives_ref *[]yaml_tag_directive_t) bool { + + var version_directive *yaml_version_directive_t + var tag_directives []yaml_tag_directive_t + + token := peek_token(parser) + if token == nil { + return false + } + + for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { + if version_directive != nil { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token.start_mark) + return false + } + if token.major != 1 || token.minor != 1 { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token.start_mark) + return false + } + version_directive = &yaml_version_directive_t{ + major: token.major, + minor: token.minor, + } + } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { + value := yaml_tag_directive_t{ + handle: token.value, + prefix: token.prefix, + } + if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { + return false + } + tag_directives = append(tag_directives, value) + } + + skip_token(parser) + token = peek_token(parser) + if token == nil { + return false + } + } + + for i := range default_tag_directives { + if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { + return false + } + } + + if version_directive_ref != nil { + *version_directive_ref = version_directive + } + if tag_directives_ref != nil { + *tag_directives_ref = tag_directives + } + return true +} + +// Append a tag directive to the directives stack. +func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { + for i := range parser.tag_directives { + if bytes.Equal(value.handle, parser.tag_directives[i].handle) { + if allow_duplicates { + return true + } + return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) + } + } + + // [Go] I suspect the copy is unnecessary. This was likely done + // because there was no way to track ownership of the data. + value_copy := yaml_tag_directive_t{ + handle: make([]byte, len(value.handle)), + prefix: make([]byte, len(value.prefix)), + } + copy(value_copy.handle, value.handle) + copy(value_copy.prefix, value.prefix) + parser.tag_directives = append(parser.tag_directives, value_copy) + return true +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/readerc.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/readerc.go new file mode 100644 index 0000000000..7c1f5fac3d --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/readerc.go @@ -0,0 +1,412 @@ +package yaml + +import ( + "io" +) + +// Set the reader error and return 0. +func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { + parser.error = yaml_READER_ERROR + parser.problem = problem + parser.problem_offset = offset + parser.problem_value = value + return false +} + +// Byte order marks. +const ( + bom_UTF8 = "\xef\xbb\xbf" + bom_UTF16LE = "\xff\xfe" + bom_UTF16BE = "\xfe\xff" +) + +// Determine the input stream encoding by checking the BOM symbol. If no BOM is +// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. +func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { + // Ensure that we had enough bytes in the raw buffer. + for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { + if !yaml_parser_update_raw_buffer(parser) { + return false + } + } + + // Determine the encoding. + buf := parser.raw_buffer + pos := parser.raw_buffer_pos + avail := len(buf) - pos + if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { + parser.encoding = yaml_UTF16LE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { + parser.encoding = yaml_UTF16BE_ENCODING + parser.raw_buffer_pos += 2 + parser.offset += 2 + } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { + parser.encoding = yaml_UTF8_ENCODING + parser.raw_buffer_pos += 3 + parser.offset += 3 + } else { + parser.encoding = yaml_UTF8_ENCODING + } + return true +} + +// Update the raw buffer. +func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { + size_read := 0 + + // Return if the raw buffer is full. + if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { + return true + } + + // Return on EOF. + if parser.eof { + return true + } + + // Move the remaining bytes in the raw buffer to the beginning. + if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { + copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) + } + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] + parser.raw_buffer_pos = 0 + + // Call the read handler to fill the buffer. + size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) + parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] + if err == io.EOF { + parser.eof = true + } else if err != nil { + return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) + } + return true +} + +// Ensure that the buffer contains at least `length` characters. +// Return true on success, false on failure. +// +// The length is supposed to be significantly less that the buffer size. +func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { + if parser.read_handler == nil { + panic("read handler must be set") + } + + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + + // If the EOF flag is set and the raw buffer is empty, do nothing. + if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true + } + + // Return if the buffer contains enough characters. + if parser.unread >= length { + return true + } + + // Determine the input encoding if it is not known yet. + if parser.encoding == yaml_ANY_ENCODING { + if !yaml_parser_determine_encoding(parser) { + return false + } + } + + // Move the unread characters to the beginning of the buffer. + buffer_len := len(parser.buffer) + if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { + copy(parser.buffer, parser.buffer[parser.buffer_pos:]) + buffer_len -= parser.buffer_pos + parser.buffer_pos = 0 + } else if parser.buffer_pos == buffer_len { + buffer_len = 0 + parser.buffer_pos = 0 + } + + // Open the whole buffer for writing, and cut it before returning. + parser.buffer = parser.buffer[:cap(parser.buffer)] + + // Fill the buffer until it has enough characters. + first := true + for parser.unread < length { + + // Fill the raw buffer if necessary. + if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { + if !yaml_parser_update_raw_buffer(parser) { + parser.buffer = parser.buffer[:buffer_len] + return false + } + } + first = false + + // Decode the raw buffer. + inner: + for parser.raw_buffer_pos != len(parser.raw_buffer) { + var value rune + var width int + + raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos + + // Decode the next character. + switch parser.encoding { + case yaml_UTF8_ENCODING: + // Decode a UTF-8 character. Check RFC 3629 + // (http://www.ietf.org/rfc/rfc3629.txt) for more details. + // + // The following table (taken from the RFC) is used for + // decoding. + // + // Char. number range | UTF-8 octet sequence + // (hexadecimal) | (binary) + // --------------------+------------------------------------ + // 0000 0000-0000 007F | 0xxxxxxx + // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + // + // Additionally, the characters in the range 0xD800-0xDFFF + // are prohibited as they are reserved for use with UTF-16 + // surrogate pairs. + + // Determine the length of the UTF-8 sequence. + octet := parser.raw_buffer[parser.raw_buffer_pos] + switch { + case octet&0x80 == 0x00: + width = 1 + case octet&0xE0 == 0xC0: + width = 2 + case octet&0xF0 == 0xE0: + width = 3 + case octet&0xF8 == 0xF0: + width = 4 + default: + // The leading octet is invalid. + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser.offset, int(octet)) + } + + // Check if the raw buffer contains an incomplete character. + if width > raw_unread { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser.offset, -1) + } + break inner + } + + // Decode the leading octet. + switch { + case octet&0x80 == 0x00: + value = rune(octet & 0x7F) + case octet&0xE0 == 0xC0: + value = rune(octet & 0x1F) + case octet&0xF0 == 0xE0: + value = rune(octet & 0x0F) + case octet&0xF8 == 0xF0: + value = rune(octet & 0x07) + default: + value = 0 + } + + // Check and decode the trailing octets. + for k := 1; k < width; k++ { + octet = parser.raw_buffer[parser.raw_buffer_pos+k] + + // Check if the octet is valid. + if (octet & 0xC0) != 0x80 { + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser.offset+k, int(octet)) + } + + // Decode the octet. + value = (value << 6) + rune(octet&0x3F) + } + + // Check the length of the sequence against the value. + switch { + case width == 1: + case width == 2 && value >= 0x80: + case width == 3 && value >= 0x800: + case width == 4 && value >= 0x10000: + default: + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser.offset, -1) + } + + // Check the range of the value. + if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser.offset, int(value)) + } + + case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: + var low, high int + if parser.encoding == yaml_UTF16LE_ENCODING { + low, high = 0, 1 + } else { + low, high = 1, 0 + } + + // The UTF-16 encoding is not as simple as one might + // naively think. Check RFC 2781 + // (http://www.ietf.org/rfc/rfc2781.txt). + // + // Normally, two subsequent bytes describe a Unicode + // character. However a special technique (called a + // surrogate pair) is used for specifying character + // values larger than 0xFFFF. + // + // A surrogate pair consists of two pseudo-characters: + // high surrogate area (0xD800-0xDBFF) + // low surrogate area (0xDC00-0xDFFF) + // + // The following formulas are used for decoding + // and encoding characters using surrogate pairs: + // + // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + // W1 = 110110yyyyyyyyyy + // W2 = 110111xxxxxxxxxx + // + // where U is the character value, W1 is the high surrogate + // area, W2 is the low surrogate area. + + // Check for incomplete UTF-16 character. + if raw_unread < 2 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser.offset, -1) + } + break inner + } + + // Get the character. + value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) + + // Check for unexpected low surrogate area. + if value&0xFC00 == 0xDC00 { + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser.offset, int(value)) + } + + // Check for a high surrogate area. + if value&0xFC00 == 0xD800 { + width = 4 + + // Check for incomplete surrogate pair. + if raw_unread < 4 { + if parser.eof { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser.offset, -1) + } + break inner + } + + // Get the next character. + value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) + + // Check for a low surrogate area. + if value2&0xFC00 != 0xDC00 { + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser.offset+2, int(value2)) + } + + // Generate the value of the surrogate pair. + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) + } else { + width = 2 + } + + default: + panic("impossible") + } + + // Check if the character is in the allowed range: + // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + // | [#x10000-#x10FFFF] (32 bit) + switch { + case value == 0x09: + case value == 0x0A: + case value == 0x0D: + case value >= 0x20 && value <= 0x7E: + case value == 0x85: + case value >= 0xA0 && value <= 0xD7FF: + case value >= 0xE000 && value <= 0xFFFD: + case value >= 0x10000 && value <= 0x10FFFF: + default: + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser.offset, int(value)) + } + + // Move the raw pointers. + parser.raw_buffer_pos += width + parser.offset += width + + // Finally put the character into the buffer. + if value <= 0x7F { + // 0000 0000-0000 007F . 0xxxxxxx + parser.buffer[buffer_len+0] = byte(value) + buffer_len += 1 + } else if value <= 0x7FF { + // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) + parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) + buffer_len += 2 + } else if value <= 0xFFFF { + // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) + buffer_len += 3 + } else { + // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) + parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) + parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) + parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) + buffer_len += 4 + } + + parser.unread++ + } + + // On EOF, put NUL into the buffer and return. + if parser.eof { + parser.buffer[buffer_len] = 0 + buffer_len++ + parser.unread++ + break + } + } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } + parser.buffer = parser.buffer[:buffer_len] + return true +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/resolve.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/resolve.go new file mode 100644 index 0000000000..4120e0c916 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/resolve.go @@ -0,0 +1,258 @@ +package yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, + {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, + {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, + {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, + {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, + {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, + {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", yaml_MERGE_TAG, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + // TODO This can easily be made faster and produce less garbage. + if strings.HasPrefix(tag, longTagPrefix) { + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: + return + case yaml_FLOAT_TAG: + if rtag == yaml_INT_TAG { + switch v := out.(type) { + case int64: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + case int: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == yaml_TIMESTAMP_TAG { + t, ok := parseTimestamp(in) + if ok { + return yaml_TIMESTAMP_TAG, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return yaml_FLOAT_TAG, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return yaml_INT_TAG, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) + } else { + return yaml_INT_TAG, intv + } + } + } + default: + panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") + } + } + return yaml_STR_TAG, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/scannerc.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/scannerc.go new file mode 100644 index 0000000000..0b9bb6030a --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/scannerc.go @@ -0,0 +1,2711 @@ +package yaml + +import ( + "bytes" + "fmt" +) + +// Introduction +// ************ +// +// The following notes assume that you are familiar with the YAML specification +// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in +// some cases we are less restrictive that it requires. +// +// The process of transforming a YAML stream into a sequence of events is +// divided on two steps: Scanning and Parsing. +// +// The Scanner transforms the input stream into a sequence of tokens, while the +// parser transform the sequence of tokens produced by the Scanner into a +// sequence of parsing events. +// +// The Scanner is rather clever and complicated. The Parser, on the contrary, +// is a straightforward implementation of a recursive-descendant parser (or, +// LL(1) parser, as it is usually called). +// +// Actually there are two issues of Scanning that might be called "clever", the +// rest is quite straightforward. The issues are "block collection start" and +// "simple keys". Both issues are explained below in details. +// +// Here the Scanning step is explained and implemented. We start with the list +// of all the tokens produced by the Scanner together with short descriptions. +// +// Now, tokens: +// +// STREAM-START(encoding) # The stream start. +// STREAM-END # The stream end. +// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. +// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. +// DOCUMENT-START # '---' +// DOCUMENT-END # '...' +// BLOCK-SEQUENCE-START # Indentation increase denoting a block +// BLOCK-MAPPING-START # sequence or a block mapping. +// BLOCK-END # Indentation decrease. +// FLOW-SEQUENCE-START # '[' +// FLOW-SEQUENCE-END # ']' +// BLOCK-SEQUENCE-START # '{' +// BLOCK-SEQUENCE-END # '}' +// BLOCK-ENTRY # '-' +// FLOW-ENTRY # ',' +// KEY # '?' or nothing (simple keys). +// VALUE # ':' +// ALIAS(anchor) # '*anchor' +// ANCHOR(anchor) # '&anchor' +// TAG(handle,suffix) # '!handle!suffix' +// SCALAR(value,style) # A scalar. +// +// The following two tokens are "virtual" tokens denoting the beginning and the +// end of the stream: +// +// STREAM-START(encoding) +// STREAM-END +// +// We pass the information about the input stream encoding with the +// STREAM-START token. +// +// The next two tokens are responsible for tags: +// +// VERSION-DIRECTIVE(major,minor) +// TAG-DIRECTIVE(handle,prefix) +// +// Example: +// +// %YAML 1.1 +// %TAG ! !foo +// %TAG !yaml! tag:yaml.org,2002: +// --- +// +// The correspoding sequence of tokens: +// +// STREAM-START(utf-8) +// VERSION-DIRECTIVE(1,1) +// TAG-DIRECTIVE("!","!foo") +// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") +// DOCUMENT-START +// STREAM-END +// +// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole +// line. +// +// The document start and end indicators are represented by: +// +// DOCUMENT-START +// DOCUMENT-END +// +// Note that if a YAML stream contains an implicit document (without '---' +// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be +// produced. +// +// In the following examples, we present whole documents together with the +// produced tokens. +// +// 1. An implicit document: +// +// 'a scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// STREAM-END +// +// 2. An explicit document: +// +// --- +// 'a scalar' +// ... +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// SCALAR("a scalar",single-quoted) +// DOCUMENT-END +// STREAM-END +// +// 3. Several documents in a stream: +// +// 'a scalar' +// --- +// 'another scalar' +// --- +// 'yet another scalar' +// +// Tokens: +// +// STREAM-START(utf-8) +// SCALAR("a scalar",single-quoted) +// DOCUMENT-START +// SCALAR("another scalar",single-quoted) +// DOCUMENT-START +// SCALAR("yet another scalar",single-quoted) +// STREAM-END +// +// We have already introduced the SCALAR token above. The following tokens are +// used to describe aliases, anchors, tag, and scalars: +// +// ALIAS(anchor) +// ANCHOR(anchor) +// TAG(handle,suffix) +// SCALAR(value,style) +// +// The following series of examples illustrate the usage of these tokens: +// +// 1. A recursive sequence: +// +// &A [ *A ] +// +// Tokens: +// +// STREAM-START(utf-8) +// ANCHOR("A") +// FLOW-SEQUENCE-START +// ALIAS("A") +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A tagged scalar: +// +// !!float "3.14" # A good approximation. +// +// Tokens: +// +// STREAM-START(utf-8) +// TAG("!!","float") +// SCALAR("3.14",double-quoted) +// STREAM-END +// +// 3. Various scalar styles: +// +// --- # Implicit empty plain scalars do not produce tokens. +// --- a plain scalar +// --- 'a single-quoted scalar' +// --- "a double-quoted scalar" +// --- |- +// a literal scalar +// --- >- +// a folded +// scalar +// +// Tokens: +// +// STREAM-START(utf-8) +// DOCUMENT-START +// DOCUMENT-START +// SCALAR("a plain scalar",plain) +// DOCUMENT-START +// SCALAR("a single-quoted scalar",single-quoted) +// DOCUMENT-START +// SCALAR("a double-quoted scalar",double-quoted) +// DOCUMENT-START +// SCALAR("a literal scalar",literal) +// DOCUMENT-START +// SCALAR("a folded scalar",folded) +// STREAM-END +// +// Now it's time to review collection-related tokens. We will start with +// flow collections: +// +// FLOW-SEQUENCE-START +// FLOW-SEQUENCE-END +// FLOW-MAPPING-START +// FLOW-MAPPING-END +// FLOW-ENTRY +// KEY +// VALUE +// +// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and +// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' +// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the +// indicators '?' and ':', which are used for denoting mapping keys and values, +// are represented by the KEY and VALUE tokens. +// +// The following examples show flow collections: +// +// 1. A flow sequence: +// +// [item 1, item 2, item 3] +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-SEQUENCE-START +// SCALAR("item 1",plain) +// FLOW-ENTRY +// SCALAR("item 2",plain) +// FLOW-ENTRY +// SCALAR("item 3",plain) +// FLOW-SEQUENCE-END +// STREAM-END +// +// 2. A flow mapping: +// +// { +// a simple key: a value, # Note that the KEY token is produced. +// ? a complex key: another value, +// } +// +// Tokens: +// +// STREAM-START(utf-8) +// FLOW-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// FLOW-ENTRY +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// FLOW-ENTRY +// FLOW-MAPPING-END +// STREAM-END +// +// A simple key is a key which is not denoted by the '?' indicator. Note that +// the Scanner still produce the KEY token whenever it encounters a simple key. +// +// For scanning block collections, the following tokens are used (note that we +// repeat KEY and VALUE here): +// +// BLOCK-SEQUENCE-START +// BLOCK-MAPPING-START +// BLOCK-END +// BLOCK-ENTRY +// KEY +// VALUE +// +// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation +// increase that precedes a block collection (cf. the INDENT token in Python). +// The token BLOCK-END denote indentation decrease that ends a block collection +// (cf. the DEDENT token in Python). However YAML has some syntax pecularities +// that makes detections of these tokens more complex. +// +// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators +// '-', '?', and ':' correspondingly. +// +// The following examples show how the tokens BLOCK-SEQUENCE-START, +// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: +// +// 1. Block sequences: +// +// - item 1 +// - item 2 +// - +// - item 3.1 +// - item 3.2 +// - +// key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 3.1",plain) +// BLOCK-ENTRY +// SCALAR("item 3.2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Block mappings: +// +// a simple key: a value # The KEY token is produced here. +// ? a complex key +// : another value +// a mapping: +// key 1: value 1 +// key 2: value 2 +// a sequence: +// - item 1 +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a simple key",plain) +// VALUE +// SCALAR("a value",plain) +// KEY +// SCALAR("a complex key",plain) +// VALUE +// SCALAR("another value",plain) +// KEY +// SCALAR("a mapping",plain) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML does not always require to start a new block collection from a new +// line. If the current line contains only '-', '?', and ':' indicators, a new +// block collection may start at the current line. The following examples +// illustrate this case: +// +// 1. Collections in a sequence: +// +// - - item 1 +// - item 2 +// - key 1: value 1 +// key 2: value 2 +// - ? complex key +// : complex value +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-ENTRY +// BLOCK-MAPPING-START +// KEY +// SCALAR("complex key") +// VALUE +// SCALAR("complex value") +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// 2. Collections in a mapping: +// +// ? a sequence +// : - item 1 +// - item 2 +// ? a mapping +// : key 1: value 1 +// key 2: value 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("a sequence",plain) +// VALUE +// BLOCK-SEQUENCE-START +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// KEY +// SCALAR("a mapping",plain) +// VALUE +// BLOCK-MAPPING-START +// KEY +// SCALAR("key 1",plain) +// VALUE +// SCALAR("value 1",plain) +// KEY +// SCALAR("key 2",plain) +// VALUE +// SCALAR("value 2",plain) +// BLOCK-END +// BLOCK-END +// STREAM-END +// +// YAML also permits non-indented sequences if they are included into a block +// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: +// +// key: +// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. +// - item 2 +// +// Tokens: +// +// STREAM-START(utf-8) +// BLOCK-MAPPING-START +// KEY +// SCALAR("key",plain) +// VALUE +// BLOCK-ENTRY +// SCALAR("item 1",plain) +// BLOCK-ENTRY +// SCALAR("item 2",plain) +// BLOCK-END +// + +// Ensure that the buffer contains the required number of characters. +// Return true on success, false on failure (reader error or memory error). +func cache(parser *yaml_parser_t, length int) bool { + // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) + return parser.unread >= length || yaml_parser_update_buffer(parser, length) +} + +// Advance the buffer pointer. +func skip(parser *yaml_parser_t) { + parser.mark.index++ + parser.mark.column++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) +} + +func skip_line(parser *yaml_parser_t) { + if is_crlf(parser.buffer, parser.buffer_pos) { + parser.mark.index += 2 + parser.mark.column = 0 + parser.mark.line++ + parser.unread -= 2 + parser.buffer_pos += 2 + } else if is_break(parser.buffer, parser.buffer_pos) { + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + } +} + +// Copy a character to a string buffer and advance pointers. +func read(parser *yaml_parser_t, s []byte) []byte { + w := width(parser.buffer[parser.buffer_pos]) + if w == 0 { + panic("invalid character sequence") + } + if len(s) == 0 { + s = make([]byte, 0, 32) + } + if w == 1 && len(s)+w <= cap(s) { + s = s[:len(s)+1] + s[len(s)-1] = parser.buffer[parser.buffer_pos] + parser.buffer_pos++ + } else { + s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) + parser.buffer_pos += w + } + parser.mark.index++ + parser.mark.column++ + parser.unread-- + return s +} + +// Copy a line break character to a string buffer and advance pointers. +func read_line(parser *yaml_parser_t, s []byte) []byte { + buf := parser.buffer + pos := parser.buffer_pos + switch { + case buf[pos] == '\r' && buf[pos+1] == '\n': + // CR LF . LF + s = append(s, '\n') + parser.buffer_pos += 2 + parser.mark.index++ + parser.unread-- + case buf[pos] == '\r' || buf[pos] == '\n': + // CR|LF . LF + s = append(s, '\n') + parser.buffer_pos += 1 + case buf[pos] == '\xC2' && buf[pos+1] == '\x85': + // NEL . LF + s = append(s, '\n') + parser.buffer_pos += 2 + case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): + // LS|PS . LS|PS + s = append(s, buf[parser.buffer_pos:pos+3]...) + parser.buffer_pos += 3 + default: + return s + } + parser.mark.index++ + parser.mark.column = 0 + parser.mark.line++ + parser.unread-- + return s +} + +// Get the next token. +func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { + // Erase the token object. + *token = yaml_token_t{} // [Go] Is this necessary? + + // No tokens after STREAM-END or error. + if parser.stream_end_produced || parser.error != yaml_NO_ERROR { + return true + } + + // Ensure that the tokens queue contains enough tokens. + if !parser.token_available { + if !yaml_parser_fetch_more_tokens(parser) { + return false + } + } + + // Fetch the next token from the queue. + *token = parser.tokens[parser.tokens_head] + parser.tokens_head++ + parser.tokens_parsed++ + parser.token_available = false + + if token.typ == yaml_STREAM_END_TOKEN { + parser.stream_end_produced = true + } + return true +} + +// Set the scanner error and return false. +func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { + parser.error = yaml_SCANNER_ERROR + parser.context = context + parser.context_mark = context_mark + parser.problem = problem + parser.problem_mark = parser.mark + return false +} + +func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { + context := "while parsing a tag" + if directive { + context = "while parsing a %TAG directive" + } + return yaml_parser_set_scanner_error(parser, context, context_mark, problem) +} + +func trace(args ...interface{}) func() { + pargs := append([]interface{}{"+++"}, args...) + fmt.Println(pargs...) + pargs = append([]interface{}{"---"}, args...) + return func() { fmt.Println(pargs...) } +} + +// Ensure that the tokens queue contains at least one token which can be +// returned to the Parser. +func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { + // While we need more tokens to fetch, do it. + for { + if parser.tokens_head != len(parser.tokens) { + // If queue is non-empty, check if any potential simple key may + // occupy the head position. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { + return false + } else if !valid { + break + } + } + // Fetch the next token. + if !yaml_parser_fetch_next_token(parser) { + return false + } + } + + parser.token_available = true + return true +} + +// The dispatcher for token fetchers. +func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { + // Ensure that the buffer is initialized. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we just started scanning. Fetch STREAM-START then. + if !parser.stream_start_produced { + return yaml_parser_fetch_stream_start(parser) + } + + // Eat whitespaces and comments until we reach the next token. + if !yaml_parser_scan_to_next_token(parser) { + return false + } + + // Check the indentation level against the current column. + if !yaml_parser_unroll_indent(parser, parser.mark.column) { + return false + } + + // Ensure that the buffer contains at least 4 characters. 4 is the length + // of the longest indicators ('--- ' and '... '). + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + // Is it the end of the stream? + if is_z(parser.buffer, parser.buffer_pos) { + return yaml_parser_fetch_stream_end(parser) + } + + // Is it a directive? + if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { + return yaml_parser_fetch_directive(parser) + } + + buf := parser.buffer + pos := parser.buffer_pos + + // Is it the document start indicator? + if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) + } + + // Is it the document end indicator? + if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { + return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) + } + + // Is it the flow sequence start indicator? + if buf[pos] == '[' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) + } + + // Is it the flow mapping start indicator? + if parser.buffer[parser.buffer_pos] == '{' { + return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) + } + + // Is it the flow sequence end indicator? + if parser.buffer[parser.buffer_pos] == ']' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_SEQUENCE_END_TOKEN) + } + + // Is it the flow mapping end indicator? + if parser.buffer[parser.buffer_pos] == '}' { + return yaml_parser_fetch_flow_collection_end(parser, + yaml_FLOW_MAPPING_END_TOKEN) + } + + // Is it the flow entry indicator? + if parser.buffer[parser.buffer_pos] == ',' { + return yaml_parser_fetch_flow_entry(parser) + } + + // Is it the block entry indicator? + if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { + return yaml_parser_fetch_block_entry(parser) + } + + // Is it the key indicator? + if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_key(parser) + } + + // Is it the value indicator? + if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_value(parser) + } + + // Is it an alias? + if parser.buffer[parser.buffer_pos] == '*' { + return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) + } + + // Is it an anchor? + if parser.buffer[parser.buffer_pos] == '&' { + return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) + } + + // Is it a tag? + if parser.buffer[parser.buffer_pos] == '!' { + return yaml_parser_fetch_tag(parser) + } + + // Is it a literal scalar? + if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, true) + } + + // Is it a folded scalar? + if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { + return yaml_parser_fetch_block_scalar(parser, false) + } + + // Is it a single-quoted scalar? + if parser.buffer[parser.buffer_pos] == '\'' { + return yaml_parser_fetch_flow_scalar(parser, true) + } + + // Is it a double-quoted scalar? + if parser.buffer[parser.buffer_pos] == '"' { + return yaml_parser_fetch_flow_scalar(parser, false) + } + + // Is it a plain scalar? + // + // A plain scalar may start with any non-blank characters except + // + // '-', '?', ':', ',', '[', ']', '{', '}', + // '#', '&', '*', '!', '|', '>', '\'', '\"', + // '%', '@', '`'. + // + // In the block context (and, for the '-' indicator, in the flow context + // too), it may also start with the characters + // + // '-', '?', ':' + // + // if it is followed by a non-space character. + // + // The last rule is more restrictive than the specification requires. + // [Go] Make this logic more reasonable. + //switch parser.buffer[parser.buffer_pos] { + //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': + //} + if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || + parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || + parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || + (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level == 0 && + (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && + !is_blankz(parser.buffer, parser.buffer_pos+1)) { + return yaml_parser_fetch_plain_scalar(parser) + } + + // If we don't determine the token type so far, it is an error. + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser.mark, + "found character that cannot start any token") +} + +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } + + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") + } + simple_key.possible = false + return false, true + } + return true, true +} + +// Check if a simple key may start at the current position and add it if +// needed. +func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { + // A simple key is required at the current position if the scanner is in + // the block context and the current column coincides with the indentation + // level. + + required := parser.flow_level == 0 && parser.indent == parser.mark.column + + // + // If the current position may start a simple key, save it. + // + if parser.simple_key_allowed { + simple_key := yaml_simple_key_t{ + possible: true, + required: required, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + } + + if !yaml_parser_remove_simple_key(parser) { + return false + } + parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 + } + return true +} + +// Remove a potential simple key at the current flow level. +func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { + i := len(parser.simple_keys) - 1 + if parser.simple_keys[i].possible { + // If the key is required, it is an error. + if parser.simple_keys[i].required { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", parser.simple_keys[i].mark, + "could not find expected ':'") + } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) + } + return true +} + +// max_flow_level limits the flow_level +const max_flow_level = 10000 + +// Increase the flow level and resize the simple key list if needed. +func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { + // Reset the simple key on the next level. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) + + // Increase the flow level. + parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } + return true +} + +// Decrease the flow level. +func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { + if parser.flow_level > 0 { + parser.flow_level-- + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] + } + return true +} + +// max_indents limits the indents stack size +const max_indents = 10000 + +// Push the current indentation level to the stack and set the new level +// the current column is greater than the indentation level. In this case, +// append or insert the specified token into the token queue. +func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + if parser.indent < column { + // Push the current indentation level to the stack and set the new + // indentation level. + parser.indents = append(parser.indents, parser.indent) + parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } + + // Create a token and insert it into the queue. + token := yaml_token_t{ + typ: typ, + start_mark: mark, + end_mark: mark, + } + if number > -1 { + number -= parser.tokens_parsed + } + yaml_insert_token(parser, number, &token) + } + return true +} + +// Pop indentation levels from the indents stack until the current level +// becomes less or equal to the column. For each indentation level, append +// the BLOCK-END token. +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { + // In the flow context, do nothing. + if parser.flow_level > 0 { + return true + } + + // Loop through the indentation levels in the stack. + for parser.indent > column { + // Create a token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + + // Pop the indentation level. + parser.indent = parser.indents[len(parser.indents)-1] + parser.indents = parser.indents[:len(parser.indents)-1] + } + return true +} + +// Initialize the scanner and produce the STREAM-START token. +func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { + + // Set the initial indentation. + parser.indent = -1 + + // Initialize the simple key stack. + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + + parser.simple_keys_by_tok = make(map[int]int) + + // A simple key is allowed at the beginning of the stream. + parser.simple_key_allowed = true + + // We have started. + parser.stream_start_produced = true + + // Create the STREAM-START token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_START_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + encoding: parser.encoding, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the STREAM-END token and shut down the scanner. +func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { + + // Force new line. + if parser.mark.column != 0 { + parser.mark.column = 0 + parser.mark.line++ + } + + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the STREAM-END token and append it to the queue. + token := yaml_token_t{ + typ: yaml_STREAM_END_TOKEN, + start_mark: parser.mark, + end_mark: parser.mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. +func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. + token := yaml_token_t{} + if !yaml_parser_scan_directive(parser, &token) { + return false + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the DOCUMENT-START or DOCUMENT-END token. +func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset the indentation level. + if !yaml_parser_unroll_indent(parser, -1) { + return false + } + + // Reset simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + parser.simple_key_allowed = false + + // Consume the token. + start_mark := parser.mark + + skip(parser) + skip(parser) + skip(parser) + + end_mark := parser.mark + + // Create the DOCUMENT-START or DOCUMENT-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. +func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // The indicators '[' and '{' may start a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // Increase the flow level. + if !yaml_parser_increase_flow_level(parser) { + return false + } + + // A simple key may follow the indicators '[' and '{'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. +func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // Reset any potential simple key on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Decrease the flow level. + if !yaml_parser_decrease_flow_level(parser) { + return false + } + + // No simple keys after the indicators ']' and '}'. + parser.simple_key_allowed = false + + // Consume the token. + + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. + token := yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + } + // Append the token to the queue. + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the FLOW-ENTRY token. +func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after ','. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the FLOW-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_FLOW_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the BLOCK-ENTRY token. +func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { + // Check if the scanner is in the block context. + if parser.flow_level == 0 { + // Check if we are allowed to start a new entry. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "block sequence entries are not allowed in this context") + } + // Add the BLOCK-SEQUENCE-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { + return false + } + } else { + // It is an error for the '-' indicator to occur in the flow context, + // but we let the Parser detect and report about it because the Parser + // is able to point to the context. + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '-'. + parser.simple_key_allowed = true + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the BLOCK-ENTRY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_BLOCK_ENTRY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the KEY token. +func yaml_parser_fetch_key(parser *yaml_parser_t) bool { + + // In the block context, additional checks are required. + if parser.flow_level == 0 { + // Check if we are allowed to start a new key (not nessesary simple). + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping keys are not allowed in this context") + } + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Reset any potential simple keys on the current flow level. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // Simple keys are allowed after '?' in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the KEY token and append it to the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the VALUE token. +func yaml_parser_fetch_value(parser *yaml_parser_t) bool { + + simple_key := &parser.simple_keys[len(parser.simple_keys)-1] + + // Have we found a simple key? + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + + // Create the KEY token and insert it into the queue. + token := yaml_token_t{ + typ: yaml_KEY_TOKEN, + start_mark: simple_key.mark, + end_mark: simple_key.mark, + } + yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) + + // In the block context, we may need to add the BLOCK-MAPPING-START token. + if !yaml_parser_roll_indent(parser, simple_key.mark.column, + simple_key.token_number, + yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { + return false + } + + // Remove the simple key. + simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) + + // A simple key cannot follow another simple key. + parser.simple_key_allowed = false + + } else { + // The ':' indicator follows a complex key. + + // In the block context, extra checks are required. + if parser.flow_level == 0 { + + // Check if we are allowed to start a complex value. + if !parser.simple_key_allowed { + return yaml_parser_set_scanner_error(parser, "", parser.mark, + "mapping values are not allowed in this context") + } + + // Add the BLOCK-MAPPING-START token if needed. + if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { + return false + } + } + + // Simple keys after ':' are allowed in the block context. + parser.simple_key_allowed = parser.flow_level == 0 + } + + // Consume the token. + start_mark := parser.mark + skip(parser) + end_mark := parser.mark + + // Create the VALUE token and append it to the queue. + token := yaml_token_t{ + typ: yaml_VALUE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the ALIAS or ANCHOR token. +func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // An anchor or an alias could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow an anchor or an alias. + parser.simple_key_allowed = false + + // Create the ALIAS or ANCHOR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_anchor(parser, &token, typ) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the TAG token. +func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { + // A tag could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a tag. + parser.simple_key_allowed = false + + // Create the TAG token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_tag(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. +func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { + // Remove any potential simple keys. + if !yaml_parser_remove_simple_key(parser) { + return false + } + + // A simple key may follow a block scalar. + parser.simple_key_allowed = true + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_block_scalar(parser, &token, literal) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. +func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_flow_scalar(parser, &token, single) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Produce the SCALAR(...,plain) token. +func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { + // A plain scalar could be a simple key. + if !yaml_parser_save_simple_key(parser) { + return false + } + + // A simple key cannot follow a flow scalar. + parser.simple_key_allowed = false + + // Create the SCALAR token and append it to the queue. + var token yaml_token_t + if !yaml_parser_scan_plain_scalar(parser, &token) { + return false + } + yaml_insert_token(parser, -1, &token) + return true +} + +// Eat whitespaces and comments until the next token is found. +func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + + // Until the next token is not found. + for { + // Allow the BOM mark to start a line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { + skip(parser) + } + + // Eat whitespaces. + // Tabs are allowed: + // - in the flow context + // - in the block context, but not at the beginning of the line or + // after '-', '?', or ':' (complex value). + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Eat a comment until a line break. + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // If it is a line break, eat it. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + + // In the block context, a new line may start a simple key. + if parser.flow_level == 0 { + parser.simple_key_allowed = true + } + } else { + break // We have found a token. + } + } + + return true +} + +// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { + // Eat '%'. + start_mark := parser.mark + skip(parser) + + // Scan the directive name. + var name []byte + if !yaml_parser_scan_directive_name(parser, start_mark, &name) { + return false + } + + // Is it a YAML directive? + if bytes.Equal(name, []byte("YAML")) { + // Scan the VERSION directive value. + var major, minor int8 + if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { + return false + } + end_mark := parser.mark + + // Create a VERSION-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_VERSION_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + major: major, + minor: minor, + } + + // Is it a TAG directive? + } else if bytes.Equal(name, []byte("TAG")) { + // Scan the TAG directive value. + var handle, prefix []byte + if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { + return false + } + end_mark := parser.mark + + // Create a TAG-DIRECTIVE token. + *token = yaml_token_t{ + typ: yaml_TAG_DIRECTIVE_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + prefix: prefix, + } + + // Unknown directive. + } else { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name") + return false + } + + // Eat the rest of the line including any comments. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + return true +} + +// Scan the directive name. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ +// +func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { + // Consume the directive name. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + var s []byte + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the name is empty. + if len(s) == 0 { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name") + return false + } + + // Check for an blank character after the name. + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character") + return false + } + *name = s + return true +} + +// Scan the value of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^ +func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the major version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { + return false + } + + // Eat '.'. + if parser.buffer[parser.buffer_pos] != '.' { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character") + } + + skip(parser) + + // Consume the minor version number. + if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { + return false + } + return true +} + +const max_number_length = 2 + +// Scan the version number of VERSION-DIRECTIVE. +// +// Scope: +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ +func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { + + // Repeat while the next character is digit. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var value, length int8 + for is_digit(parser.buffer, parser.buffer_pos) { + // Check if the number is too long. + length++ + if length > max_number_length { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number") + } + value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the number was present. + if length == 0 { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number") + } + *number = value + return true +} + +// Scan the value of a TAG-DIRECTIVE token. +// +// Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// +func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { + var handle_value, prefix_value []byte + + // Eat whitespaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a handle. + if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { + return false + } + + // Expect a whitespace. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blank(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace") + return false + } + + // Eat whitespaces. + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Scan a prefix. + if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { + return false + } + + // Expect a whitespace or line break. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break") + return false + } + + *handle = handle_value + *prefix = prefix_value + return true +} + +func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { + var s []byte + + // Eat the indicator character. + start_mark := parser.mark + skip(parser) + + // Consume the value. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + end_mark := parser.mark + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if len(s) == 0 || + !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || + parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '`') { + context := "while scanning an alias" + if typ == yaml_ANCHOR_TOKEN { + context = "while scanning an anchor" + } + yaml_parser_set_scanner_error(parser, context, start_mark, + "did not find expected alphabetic or numeric character") + return false + } + + // Create a token. + *token = yaml_token_t{ + typ: typ, + start_mark: start_mark, + end_mark: end_mark, + value: s, + } + + return true +} + +/* + * Scan a TAG token. + */ + +func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { + var handle, suffix []byte + + start_mark := parser.mark + + // Check if the tag is in the canonical form. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + if parser.buffer[parser.buffer_pos+1] == '<' { + // Keep the handle as '' + + // Eat '!<' + skip(parser) + skip(parser) + + // Consume the tag value. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + + // Check for '>' and eat it. + if parser.buffer[parser.buffer_pos] != '>' { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'") + return false + } + + skip(parser) + } else { + // The tag has either the '!suffix' or the '!handle!suffix' form. + + // First, try to scan a handle. + if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { + return false + } + + // Check if it is, indeed, handle. + if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { + // Scan the suffix now. + if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { + return false + } + } else { + // It wasn't a handle after all. Scan the rest of the tag. + if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { + return false + } + + // Set the handle to '!'. + handle = []byte{'!'} + + // A special case: the '!' tag. Set the handle to '' and the + // suffix to '!'. + if len(suffix) == 0 { + handle, suffix = suffix, handle + } + } + } + + // Check the character which ends the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if !is_blankz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break") + return false + } + + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_TAG_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: handle, + suffix: suffix, + } + return true +} + +// Scan a tag handle. +func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { + // Check the initial '!' character. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] != '!' { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + + var s []byte + + // Copy the '!' character. + s = read(parser, s) + + // Copy all subsequent alphabetical and numerical characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_alpha(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check if the trailing character is '!' and copy it. + if parser.buffer[parser.buffer_pos] == '!' { + s = read(parser, s) + } else { + // It's either the '!' tag or not really a tag handle. If it's a %TAG + // directive, it's an error. If it's a tag token, it must be a part of URI. + if directive && string(s) != "!" { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected '!'") + return false + } + } + + *handle = s + return true +} + +// Scan a tag. +func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { + //size_t length = head ? strlen((char *)head) : 0 + var s []byte + hasTag := len(head) > 0 + + // Copy the head if needed. + // + // Note that we don't copy the leading '!' character. + if len(head) > 1 { + s = append(s, head[1:]...) + } + + // Scan the tag. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // The set of characters that may appear in URI is as follows: + // + // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', + // '%'. + // [Go] Convert this into more reasonable logic. + for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || + parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || + parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || + parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || + parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || + parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || + parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || + parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || + parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || + parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || + parser.buffer[parser.buffer_pos] == '%' { + // Check if it is a URI-escape sequence. + if parser.buffer[parser.buffer_pos] == '%' { + if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { + return false + } + } else { + s = read(parser, s) + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + hasTag = true + } + + if !hasTag { + yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find expected tag URI") + return false + } + *uri = s + return true +} + +// Decode an URI-escape sequence corresponding to a single UTF-8 character. +func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { + + // Decode the required number of characters. + w := 1024 + for w > 0 { + // Check for a URI-escaped octet. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + + if !(parser.buffer[parser.buffer_pos] == '%' && + is_hex(parser.buffer, parser.buffer_pos+1) && + is_hex(parser.buffer, parser.buffer_pos+2)) { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "did not find URI escaped octet") + } + + // Get the octet. + octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) + + // If it is the leading octet, determine the length of the UTF-8 sequence. + if w == 1024 { + w = width(octet) + if w == 0 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect leading UTF-8 octet") + } + } else { + // Check if the trailing octet is correct. + if octet&0xC0 != 0x80 { + return yaml_parser_set_scanner_tag_error(parser, directive, + start_mark, "found an incorrect trailing UTF-8 octet") + } + } + + // Copy the octet and move the pointers. + *s = append(*s, octet) + skip(parser) + skip(parser) + skip(parser) + w-- + } + return true +} + +// Scan a block scalar. +func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { + // Eat the indicator '|' or '>'. + start_mark := parser.mark + skip(parser) + + // Scan the additional block scalar indicators. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check for a chomping indicator. + var chomping, increment int + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + // Set the chomping method and eat the indicator. + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + + // Check for an indentation indicator. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_digit(parser.buffer, parser.buffer_pos) { + // Check that the indentation is greater than 0. + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + + // Get the indentation level and eat the indicator. + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + } + + } else if is_digit(parser.buffer, parser.buffer_pos) { + // Do the same as above, but in the opposite order. + + if parser.buffer[parser.buffer_pos] == '0' { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0") + return false + } + increment = as_digit(parser.buffer, parser.buffer_pos) + skip(parser) + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { + if parser.buffer[parser.buffer_pos] == '+' { + chomping = +1 + } else { + chomping = -1 + } + skip(parser) + } + } + + // Eat whitespaces and comments to the end of the line. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for is_blank(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.buffer[parser.buffer_pos] == '#' { + for !is_breakz(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + } + + // Check if we are at the end of the line. + if !is_breakz(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break") + return false + } + + // Eat a line break. + if is_break(parser.buffer, parser.buffer_pos) { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } + + end_mark := parser.mark + + // Set the indentation level if it was specified. + var indent int + if increment > 0 { + if parser.indent >= 0 { + indent = parser.indent + increment + } else { + indent = increment + } + } + + // Scan the leading line breaks and determine the indentation level if needed. + var s, leading_break, trailing_breaks []byte + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + + // Scan the block scalar content. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + var leading_blank, trailing_blank bool + for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { + // We are at the beginning of a non-empty line. + + // Is it a trailing whitespace? + trailing_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Check if we need to fold the leading line break. + if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { + // Do we need to join the lines by space? + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } + } else { + s = append(s, leading_break...) + } + leading_break = leading_break[:0] + + // Append the remaining line breaks. + s = append(s, trailing_breaks...) + trailing_breaks = trailing_breaks[:0] + + // Is it a leading whitespace? + leading_blank = is_blank(parser.buffer, parser.buffer_pos) + + // Consume the current line. + for !is_breakz(parser.buffer, parser.buffer_pos) { + s = read(parser, s) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + leading_break = read_line(parser, leading_break) + + // Eat the following indentation spaces and line breaks. + if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { + return false + } + } + + // Chomp the tail. + if chomping != -1 { + s = append(s, leading_break...) + } + if chomping == 1 { + s = append(s, trailing_breaks...) + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_LITERAL_SCALAR_STYLE, + } + if !literal { + token.style = yaml_FOLDED_SCALAR_STYLE + } + return true +} + +// Scan indentation spaces and line breaks for a block scalar. Determine the +// indentation level if needed. +func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { + *end_mark = parser.mark + + // Eat the indentation spaces and line breaks. + max_indent := 0 + for { + // Eat the indentation spaces. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { + skip(parser) + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + if parser.mark.column > max_indent { + max_indent = parser.mark.column + } + + // Check for a tab character messing the indentation. + if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected") + } + + // Have we found a non-empty line? + if !is_break(parser.buffer, parser.buffer_pos) { + break + } + + // Consume the line break. + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + // [Go] Should really be returning breaks instead. + *breaks = read_line(parser, *breaks) + *end_mark = parser.mark + } + + // Determine the indentation level if needed. + if *indent == 0 { + *indent = max_indent + if *indent < parser.indent+1 { + *indent = parser.indent + 1 + } + if *indent < 1 { + *indent = 1 + } + } + return true +} + +// Scan a quoted scalar. +func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { + // Eat the left quote. + start_mark := parser.mark + skip(parser) + + // Consume the content of the quoted scalar. + var s, leading_break, trailing_breaks, whitespaces []byte + for { + // Check that there are no document indicators at the beginning of the line. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator") + return false + } + + // Check for EOF. + if is_z(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream") + return false + } + + // Consume non-blank characters. + leading_blanks := false + for !is_blankz(parser.buffer, parser.buffer_pos) { + if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { + // Is is an escaped single quote. + s = append(s, '\'') + skip(parser) + skip(parser) + + } else if single && parser.buffer[parser.buffer_pos] == '\'' { + // It is a right single quote. + break + } else if !single && parser.buffer[parser.buffer_pos] == '"' { + // It is a right double quote. + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { + // It is an escaped line break. + if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { + return false + } + skip(parser) + skip_line(parser) + leading_blanks = true + break + + } else if !single && parser.buffer[parser.buffer_pos] == '\\' { + // It is an escape sequence. + code_length := 0 + + // Check the escape character. + switch parser.buffer[parser.buffer_pos+1] { + case '0': + s = append(s, 0) + case 'a': + s = append(s, '\x07') + case 'b': + s = append(s, '\x08') + case 't', '\t': + s = append(s, '\x09') + case 'n': + s = append(s, '\x0A') + case 'v': + s = append(s, '\x0B') + case 'f': + s = append(s, '\x0C') + case 'r': + s = append(s, '\x0D') + case 'e': + s = append(s, '\x1B') + case ' ': + s = append(s, '\x20') + case '"': + s = append(s, '"') + case '\'': + s = append(s, '\'') + case '\\': + s = append(s, '\\') + case 'N': // NEL (#x85) + s = append(s, '\xC2') + s = append(s, '\x85') + case '_': // #xA0 + s = append(s, '\xC2') + s = append(s, '\xA0') + case 'L': // LS (#x2028) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA8') + case 'P': // PS (#x2029) + s = append(s, '\xE2') + s = append(s, '\x80') + s = append(s, '\xA9') + case 'x': + code_length = 2 + case 'u': + code_length = 4 + case 'U': + code_length = 8 + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character") + return false + } + + skip(parser) + skip(parser) + + // Consume an arbitrary escape code. + if code_length > 0 { + var value int + + // Scan the character value. + if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { + return false + } + for k := 0; k < code_length; k++ { + if !is_hex(parser.buffer, parser.buffer_pos+k) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number") + return false + } + value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) + } + + // Check the value and write the character. + if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code") + return false + } + if value <= 0x7F { + s = append(s, byte(value)) + } else if value <= 0x7FF { + s = append(s, byte(0xC0+(value>>6))) + s = append(s, byte(0x80+(value&0x3F))) + } else if value <= 0xFFFF { + s = append(s, byte(0xE0+(value>>12))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } else { + s = append(s, byte(0xF0+(value>>18))) + s = append(s, byte(0x80+((value>>12)&0x3F))) + s = append(s, byte(0x80+((value>>6)&0x3F))) + s = append(s, byte(0x80+(value&0x3F))) + } + + // Advance the pointer. + for k := 0; k < code_length; k++ { + skip(parser) + } + } + } else { + // It is a non-escaped non-blank character. + s = read(parser, s) + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + // Check if we are at the end of the scalar. + if single { + if parser.buffer[parser.buffer_pos] == '\'' { + break + } + } else { + if parser.buffer[parser.buffer_pos] == '"' { + break + } + } + + // Consume blank characters. + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Join the whitespaces or fold line breaks. + if leading_blanks { + // Do we need to fold line breaks? + if len(leading_break) > 0 && leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Eat the right quote. + skip(parser) + end_mark := parser.mark + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_SINGLE_QUOTED_SCALAR_STYLE, + } + if !single { + token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + return true +} + +// Scan a plain scalar. +func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { + + var s, leading_break, trailing_breaks, whitespaces []byte + var leading_blanks bool + var indent = parser.indent + 1 + + start_mark := parser.mark + end_mark := parser.mark + + // Consume the content of the plain scalar. + for { + // Check for a document indicator. + if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { + return false + } + if parser.mark.column == 0 && + ((parser.buffer[parser.buffer_pos+0] == '-' && + parser.buffer[parser.buffer_pos+1] == '-' && + parser.buffer[parser.buffer_pos+2] == '-') || + (parser.buffer[parser.buffer_pos+0] == '.' && + parser.buffer[parser.buffer_pos+1] == '.' && + parser.buffer[parser.buffer_pos+2] == '.')) && + is_blankz(parser.buffer, parser.buffer_pos+3) { + break + } + + // Check for a comment. + if parser.buffer[parser.buffer_pos] == '#' { + break + } + + // Consume non-blank characters. + for !is_blankz(parser.buffer, parser.buffer_pos) { + + // Check for indicators that may end a plain scalar. + if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || + (parser.flow_level > 0 && + (parser.buffer[parser.buffer_pos] == ',' || + parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || + parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || + parser.buffer[parser.buffer_pos] == '}')) { + break + } + + // Check if we need to join whitespaces and breaks. + if leading_blanks || len(whitespaces) > 0 { + if leading_blanks { + // Do we need to fold line breaks? + if leading_break[0] == '\n' { + if len(trailing_breaks) == 0 { + s = append(s, ' ') + } else { + s = append(s, trailing_breaks...) + } + } else { + s = append(s, leading_break...) + s = append(s, trailing_breaks...) + } + trailing_breaks = trailing_breaks[:0] + leading_break = leading_break[:0] + leading_blanks = false + } else { + s = append(s, whitespaces...) + whitespaces = whitespaces[:0] + } + } + + // Copy the character. + s = read(parser, s) + + end_mark = parser.mark + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + } + + // Is it the end? + if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { + break + } + + // Consume blank characters. + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + + for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { + if is_blank(parser.buffer, parser.buffer_pos) { + + // Check for tab characters that abuse indentation. + if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation") + return false + } + + // Consume a space or a tab character. + if !leading_blanks { + whitespaces = read(parser, whitespaces) + } else { + skip(parser) + } + } else { + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + + // Check if it is a first line break. + if !leading_blanks { + whitespaces = whitespaces[:0] + leading_break = read_line(parser, leading_break) + leading_blanks = true + } else { + trailing_breaks = read_line(parser, trailing_breaks) + } + } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + } + + // Check indentation level. + if parser.flow_level == 0 && parser.mark.column < indent { + break + } + } + + // Create a token. + *token = yaml_token_t{ + typ: yaml_SCALAR_TOKEN, + start_mark: start_mark, + end_mark: end_mark, + value: s, + style: yaml_PLAIN_SCALAR_STYLE, + } + + // Note that we change the 'simple_key_allowed' flag. + if leading_blanks { + parser.simple_key_allowed = true + } + return true +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/sorter.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/sorter.go new file mode 100644 index 0000000000..4c45e660a8 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/sorter.go @@ -0,0 +1,113 @@ +package yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + return bl + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/writerc.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/writerc.go new file mode 100644 index 0000000000..a2dde608cb --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/writerc.go @@ -0,0 +1,26 @@ +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/yaml.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/yaml.go new file mode 100644 index 0000000000..30813884c0 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/yaml.go @@ -0,0 +1,478 @@ +// Package yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/go-yaml/yaml +// +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" +) + +// MapSlice encodes and decodes as a YAML map. +// The order of keys is preserved when encoding and decoding. +type MapSlice []MapItem + +// MapItem is an item in a MapSlice. +type MapItem struct { + Key, Value interface{} +} + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. The UnmarshalYAML +// method receives a function that may be called to unmarshal the original +// YAML value into a field or variable. It is safe to call the unmarshal +// function parameter more than once if necessary. +type Unmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +// +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// UnmarshalStrict is like Unmarshal except that any fields that are found +// in the data that do not have corresponding struct members, or mapping +// keys that are duplicates, will result in +// an error. +func UnmarshalStrict(in []byte, out interface{}) (err error) { + return unmarshal(in, out, true) +} + +// A Decoder reads and decodes YAML values from an input stream. +type Decoder struct { + strict bool + parser *parser +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// SetStrict sets whether strict decoding behaviour is enabled when +// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. +func (dec *Decoder) SetStrict(strict bool) { + dec.strict = strict +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder(dec.strict) + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder(strict) + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("Multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct: + sinfo, err := getStructInfo(field.Type) + if err != nil { + return nil, err + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + default: + //return nil, errors.New("Option ,inline needs a struct value or map field") + return nil, errors.New("Option ,inline needs a struct value field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "Duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} + +// FutureLineWrap globally disables line wrapping when encoding long strings. +// This is a temporary and thus deprecated method introduced to faciliate +// migration towards v3, which offers more control of line lengths on +// individual encodings, and has a default matching the behavior introduced +// by this function. +// +// The default formatting of v2 was erroneously changed in v2.3.0 and reverted +// in v2.4.0, at which point this function was introduced to help migration. +func FutureLineWrap() { + disableLineWrapping = true +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/yamlh.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/yamlh.go new file mode 100644 index 0000000000..f6a9c8e34b --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/yamlh.go @@ -0,0 +1,739 @@ +package yaml + +import ( + "fmt" + "io" +) + +// The version directive data. +type yaml_version_directive_t struct { + major int8 // The major version number. + minor int8 // The minor version number. +} + +// The tag directive data. +type yaml_tag_directive_t struct { + handle []byte // The tag handle. + prefix []byte // The tag prefix. +} + +type yaml_encoding_t int + +// The stream encoding. +const ( + // Let the parser choose the encoding. + yaml_ANY_ENCODING yaml_encoding_t = iota + + yaml_UTF8_ENCODING // The default UTF-8 encoding. + yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. + yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. +) + +type yaml_break_t int + +// Line break types. +const ( + // Let the parser choose the break type. + yaml_ANY_BREAK yaml_break_t = iota + + yaml_CR_BREAK // Use CR for line breaks (Mac style). + yaml_LN_BREAK // Use LN for line breaks (Unix style). + yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). +) + +type yaml_error_type_t int + +// Many bad things could happen with the parser and emitter. +const ( + // No error is produced. + yaml_NO_ERROR yaml_error_type_t = iota + + yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. + yaml_READER_ERROR // Cannot read or decode the input stream. + yaml_SCANNER_ERROR // Cannot scan the input stream. + yaml_PARSER_ERROR // Cannot parse the input stream. + yaml_COMPOSER_ERROR // Cannot compose a YAML document. + yaml_WRITER_ERROR // Cannot write to the output stream. + yaml_EMITTER_ERROR // Cannot emit a YAML stream. +) + +// The pointer position. +type yaml_mark_t struct { + index int // The position index. + line int // The position line. + column int // The position column. +} + +// Node Styles + +type yaml_style_t int8 + +type yaml_scalar_style_t yaml_style_t + +// Scalar styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota + + yaml_PLAIN_SCALAR_STYLE // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. +) + +type yaml_sequence_style_t yaml_style_t + +// Sequence styles. +const ( + // Let the emitter choose the style. + yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota + + yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. + yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. +) + +type yaml_mapping_style_t yaml_style_t + +// Mapping styles. +const ( + // Let the emitter choose the style. + yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota + + yaml_BLOCK_MAPPING_STYLE // The block mapping style. + yaml_FLOW_MAPPING_STYLE // The flow mapping style. +) + +// Tokens + +type yaml_token_type_t int + +// Token types. +const ( + // An empty token. + yaml_NO_TOKEN yaml_token_type_t = iota + + yaml_STREAM_START_TOKEN // A STREAM-START token. + yaml_STREAM_END_TOKEN // A STREAM-END token. + + yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. + yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. + yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. + yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. + + yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. + yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. + yaml_BLOCK_END_TOKEN // A BLOCK-END token. + + yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. + yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. + yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. + yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. + + yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. + yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. + yaml_KEY_TOKEN // A KEY token. + yaml_VALUE_TOKEN // A VALUE token. + + yaml_ALIAS_TOKEN // An ALIAS token. + yaml_ANCHOR_TOKEN // An ANCHOR token. + yaml_TAG_TOKEN // A TAG token. + yaml_SCALAR_TOKEN // A SCALAR token. +) + +func (tt yaml_token_type_t) String() string { + switch tt { + case yaml_NO_TOKEN: + return "yaml_NO_TOKEN" + case yaml_STREAM_START_TOKEN: + return "yaml_STREAM_START_TOKEN" + case yaml_STREAM_END_TOKEN: + return "yaml_STREAM_END_TOKEN" + case yaml_VERSION_DIRECTIVE_TOKEN: + return "yaml_VERSION_DIRECTIVE_TOKEN" + case yaml_TAG_DIRECTIVE_TOKEN: + return "yaml_TAG_DIRECTIVE_TOKEN" + case yaml_DOCUMENT_START_TOKEN: + return "yaml_DOCUMENT_START_TOKEN" + case yaml_DOCUMENT_END_TOKEN: + return "yaml_DOCUMENT_END_TOKEN" + case yaml_BLOCK_SEQUENCE_START_TOKEN: + return "yaml_BLOCK_SEQUENCE_START_TOKEN" + case yaml_BLOCK_MAPPING_START_TOKEN: + return "yaml_BLOCK_MAPPING_START_TOKEN" + case yaml_BLOCK_END_TOKEN: + return "yaml_BLOCK_END_TOKEN" + case yaml_FLOW_SEQUENCE_START_TOKEN: + return "yaml_FLOW_SEQUENCE_START_TOKEN" + case yaml_FLOW_SEQUENCE_END_TOKEN: + return "yaml_FLOW_SEQUENCE_END_TOKEN" + case yaml_FLOW_MAPPING_START_TOKEN: + return "yaml_FLOW_MAPPING_START_TOKEN" + case yaml_FLOW_MAPPING_END_TOKEN: + return "yaml_FLOW_MAPPING_END_TOKEN" + case yaml_BLOCK_ENTRY_TOKEN: + return "yaml_BLOCK_ENTRY_TOKEN" + case yaml_FLOW_ENTRY_TOKEN: + return "yaml_FLOW_ENTRY_TOKEN" + case yaml_KEY_TOKEN: + return "yaml_KEY_TOKEN" + case yaml_VALUE_TOKEN: + return "yaml_VALUE_TOKEN" + case yaml_ALIAS_TOKEN: + return "yaml_ALIAS_TOKEN" + case yaml_ANCHOR_TOKEN: + return "yaml_ANCHOR_TOKEN" + case yaml_TAG_TOKEN: + return "yaml_TAG_TOKEN" + case yaml_SCALAR_TOKEN: + return "yaml_SCALAR_TOKEN" + } + return "" +} + +// The token structure. +type yaml_token_t struct { + // The token type. + typ yaml_token_type_t + + // The start/end of the token. + start_mark, end_mark yaml_mark_t + + // The stream encoding (for yaml_STREAM_START_TOKEN). + encoding yaml_encoding_t + + // The alias/anchor/scalar value or tag/tag directive handle + // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). + value []byte + + // The tag suffix (for yaml_TAG_TOKEN). + suffix []byte + + // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). + prefix []byte + + // The scalar style (for yaml_SCALAR_TOKEN). + style yaml_scalar_style_t + + // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). + major, minor int8 +} + +// Events + +type yaml_event_type_t int8 + +// Event types. +const ( + // An empty event. + yaml_NO_EVENT yaml_event_type_t = iota + + yaml_STREAM_START_EVENT // A STREAM-START event. + yaml_STREAM_END_EVENT // A STREAM-END event. + yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. + yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. + yaml_ALIAS_EVENT // An ALIAS event. + yaml_SCALAR_EVENT // A SCALAR event. + yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. + yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. + yaml_MAPPING_START_EVENT // A MAPPING-START event. + yaml_MAPPING_END_EVENT // A MAPPING-END event. +) + +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + +// The event structure. +type yaml_event_t struct { + + // The event type. + typ yaml_event_type_t + + // The start and end of the event. + start_mark, end_mark yaml_mark_t + + // The document encoding (for yaml_STREAM_START_EVENT). + encoding yaml_encoding_t + + // The version directive (for yaml_DOCUMENT_START_EVENT). + version_directive *yaml_version_directive_t + + // The list of tag directives (for yaml_DOCUMENT_START_EVENT). + tag_directives []yaml_tag_directive_t + + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). + anchor []byte + + // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + tag []byte + + // The scalar value (for yaml_SCALAR_EVENT). + value []byte + + // Is the document start/end indicator implicit, or the tag optional? + // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). + implicit bool + + // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). + quoted_implicit bool + + // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). + style yaml_style_t +} + +func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } +func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } +func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } + +// Nodes + +const ( + yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. + yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. + yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. + yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. + yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. + yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. + + yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. + yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. + + // Not in original libyaml. + yaml_BINARY_TAG = "tag:yaml.org,2002:binary" + yaml_MERGE_TAG = "tag:yaml.org,2002:merge" + + yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. + yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. + yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. +) + +type yaml_node_type_t int + +// Node types. +const ( + // An empty node. + yaml_NO_NODE yaml_node_type_t = iota + + yaml_SCALAR_NODE // A scalar node. + yaml_SEQUENCE_NODE // A sequence node. + yaml_MAPPING_NODE // A mapping node. +) + +// An element of a sequence node. +type yaml_node_item_t int + +// An element of a mapping node. +type yaml_node_pair_t struct { + key int // The key of the element. + value int // The value of the element. +} + +// The node structure. +type yaml_node_t struct { + typ yaml_node_type_t // The node type. + tag []byte // The node tag. + + // The node data. + + // The scalar parameters (for yaml_SCALAR_NODE). + scalar struct { + value []byte // The scalar value. + length int // The length of the scalar value. + style yaml_scalar_style_t // The scalar style. + } + + // The sequence parameters (for YAML_SEQUENCE_NODE). + sequence struct { + items_data []yaml_node_item_t // The stack of sequence items. + style yaml_sequence_style_t // The sequence style. + } + + // The mapping parameters (for yaml_MAPPING_NODE). + mapping struct { + pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). + pairs_start *yaml_node_pair_t // The beginning of the stack. + pairs_end *yaml_node_pair_t // The end of the stack. + pairs_top *yaml_node_pair_t // The top of the stack. + style yaml_mapping_style_t // The mapping style. + } + + start_mark yaml_mark_t // The beginning of the node. + end_mark yaml_mark_t // The end of the node. + +} + +// The document structure. +type yaml_document_t struct { + + // The document nodes. + nodes []yaml_node_t + + // The version directive. + version_directive *yaml_version_directive_t + + // The list of tag directives. + tag_directives_data []yaml_tag_directive_t + tag_directives_start int // The beginning of the tag directives list. + tag_directives_end int // The end of the tag directives list. + + start_implicit int // Is the document start indicator implicit? + end_implicit int // Is the document end indicator implicit? + + // The start/end of the document. + start_mark, end_mark yaml_mark_t +} + +// The prototype of a read handler. +// +// The read handler is called when the parser needs to read more bytes from the +// source. The handler should write not more than size bytes to the buffer. +// The number of written bytes should be set to the size_read variable. +// +// [in,out] data A pointer to an application data specified by +// yaml_parser_set_input(). +// [out] buffer The buffer to write the data from the source. +// [in] size The size of the buffer. +// [out] size_read The actual number of bytes read from the source. +// +// On success, the handler should return 1. If the handler failed, +// the returned value should be 0. On EOF, the handler should set the +// size_read to 0 and return 1. +type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) + +// This structure holds information about a potential simple key. +type yaml_simple_key_t struct { + possible bool // Is a simple key possible? + required bool // Is a simple key required? + token_number int // The number of the token. + mark yaml_mark_t // The position mark. +} + +// The states of the parser. +type yaml_parser_state_t int + +const ( + yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota + + yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. + yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. + yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. + yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. + yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. + yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. + yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. + yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. + yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. + yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. + yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. + yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. + yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. + yaml_PARSE_END_STATE // Expect nothing. +) + +func (ps yaml_parser_state_t) String() string { + switch ps { + case yaml_PARSE_STREAM_START_STATE: + return "yaml_PARSE_STREAM_START_STATE" + case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_START_STATE: + return "yaml_PARSE_DOCUMENT_START_STATE" + case yaml_PARSE_DOCUMENT_CONTENT_STATE: + return "yaml_PARSE_DOCUMENT_CONTENT_STATE" + case yaml_PARSE_DOCUMENT_END_STATE: + return "yaml_PARSE_DOCUMENT_END_STATE" + case yaml_PARSE_BLOCK_NODE_STATE: + return "yaml_PARSE_BLOCK_NODE_STATE" + case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" + case yaml_PARSE_FLOW_NODE_STATE: + return "yaml_PARSE_FLOW_NODE_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: + return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" + case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: + return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" + case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_KEY_STATE: + return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" + case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" + case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" + case yaml_PARSE_END_STATE: + return "yaml_PARSE_END_STATE" + } + return "" +} + +// This structure holds aliases data. +type yaml_alias_data_t struct { + anchor []byte // The anchor. + index int // The node id. + mark yaml_mark_t // The anchor mark. +} + +// The parser structure. +// +// All members are internal. Manage the structure using the +// yaml_parser_ family of functions. +type yaml_parser_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + + problem string // Error description. + + // The byte about which the problem occurred. + problem_offset int + problem_value int + problem_mark yaml_mark_t + + // The error context. + context string + context_mark yaml_mark_t + + // Reader stuff + + read_handler yaml_read_handler_t // Read handler. + + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int + + eof bool // EOF flag + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + unread int // The number of unread characters in the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The input encoding. + + offset int // The offset of the current position (in bytes). + mark yaml_mark_t // The mark of the current position. + + // Scanner stuff + + stream_start_produced bool // Have we started to scan the input stream? + stream_end_produced bool // Have we reached the end of the input stream? + + flow_level int // The number of unclosed '[' and '{' indicators. + + tokens []yaml_token_t // The tokens queue. + tokens_head int // The head of the tokens queue. + tokens_parsed int // The number of tokens fetched from the queue. + token_available bool // Does the tokens queue contain a token ready for dequeueing. + + indent int // The current indentation level. + indents []int // The indentation levels stack. + + simple_key_allowed bool // May a simple key occur at the current position? + simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number + + // Parser stuff + + state yaml_parser_state_t // The current parser state. + states []yaml_parser_state_t // The parser states stack. + marks []yaml_mark_t // The stack of marks. + tag_directives []yaml_tag_directive_t // The list of TAG directives. + + // Dumper stuff + + aliases []yaml_alias_data_t // The alias data. + + document *yaml_document_t // The currently parsed document. +} + +// Emitter Definitions + +// The prototype of a write handler. +// +// The write handler is called when the emitter needs to flush the accumulated +// characters to the output. The handler should write @a size bytes of the +// @a buffer to the output. +// +// @param[in,out] data A pointer to an application data specified by +// yaml_emitter_set_output(). +// @param[in] buffer The buffer with bytes to be written. +// @param[in] size The size of the buffer. +// +// @returns On success, the handler should return @c 1. If the handler failed, +// the returned value should be @c 0. +// +type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error + +type yaml_emitter_state_t int + +// The emitter states. +const ( + // Expect STREAM-START. + yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota + + yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. + yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. + yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. + yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. + yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. + yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. + yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. + yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. + yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. + yaml_EMIT_END_STATE // Expect nothing. +) + +// The emitter structure. +// +// All members are internal. Manage the structure using the @c yaml_emitter_ +// family of functions. +type yaml_emitter_t struct { + + // Error handling + + error yaml_error_type_t // Error type. + problem string // Error description. + + // Writer stuff + + write_handler yaml_write_handler_t // Write handler. + + output_buffer *[]byte // String output data. + output_writer io.Writer // File output data. + + buffer []byte // The working buffer. + buffer_pos int // The current position of the buffer. + + raw_buffer []byte // The raw buffer. + raw_buffer_pos int // The current position of the buffer. + + encoding yaml_encoding_t // The stream encoding. + + // Emitter stuff + + canonical bool // If the output is in the canonical style? + best_indent int // The number of indentation spaces. + best_width int // The preferred width of the output lines. + unicode bool // Allow unescaped non-ASCII characters? + line_break yaml_break_t // The preferred line break. + + state yaml_emitter_state_t // The current emitter state. + states []yaml_emitter_state_t // The stack of states. + + events []yaml_event_t // The event queue. + events_head int // The head of the event queue. + + indents []int // The stack of indentation levels. + + tag_directives []yaml_tag_directive_t // The list of tag directives. + + indent int // The current indentation level. + + flow_level int // The current flow level. + + root_context bool // Is it the document root context? + sequence_context bool // Is it a sequence context? + mapping_context bool // Is it a mapping context? + simple_key_context bool // Is it a simple mapping key context? + + line int // The current line. + column int // The current column. + whitespace bool // If the last character was a whitespace? + indention bool // If the last character was an indentation character (' ', '-', '?', ':')? + open_ended bool // If an explicit document end is required? + + // Anchor analysis. + anchor_data struct { + anchor []byte // The anchor value. + alias bool // Is it an alias? + } + + // Tag analysis. + tag_data struct { + handle []byte // The tag handle. + suffix []byte // The tag suffix. + } + + // Scalar analysis. + scalar_data struct { + value []byte // The scalar value. + multiline bool // Does the scalar contain line breaks? + flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? + block_plain_allowed bool // Can the scalar be expressed in the block plain style? + single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? + block_allowed bool // Can the scalar be expressed in the literal or folded styles? + style yaml_scalar_style_t // The output style. + } + + // Dumper stuff + + opened bool // If the stream was already opened? + closed bool // If the stream was already closed? + + // The information associated with the document nodes. + anchors *struct { + references int // The number of references. + anchor int // The anchor id. + serialized bool // If the node has been emitted? + } + + last_anchor_id int // The last assigned anchor id. + + document *yaml_document_t // The currently emitted document. +} diff --git a/vendor/sigs.k8s.io/yaml/goyaml.v2/yamlprivateh.go b/vendor/sigs.k8s.io/yaml/goyaml.v2/yamlprivateh.go new file mode 100644 index 0000000000..8110ce3c37 --- /dev/null +++ b/vendor/sigs.k8s.io/yaml/goyaml.v2/yamlprivateh.go @@ -0,0 +1,173 @@ +package yaml + +const ( + // The size of the input raw buffer. + input_raw_buffer_size = 512 + + // The size of the input buffer. + // It should be possible to decode the whole raw buffer. + input_buffer_size = input_raw_buffer_size * 3 + + // The size of the output buffer. + output_buffer_size = 128 + + // The size of the output raw buffer. + // It should be possible to encode the whole output buffer. + output_raw_buffer_size = (output_buffer_size*2 + 2) + + // The size of other stacks and queues. + initial_stack_size = 16 + initial_queue_size = 16 + initial_string_size = 16 +) + +// Check if the character at the specified position is an alphabetical +// character, a digit, '_', or '-'. +func is_alpha(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' +} + +// Check if the character at the specified position is a digit. +func is_digit(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' +} + +// Get the value of a digit. +func as_digit(b []byte, i int) int { + return int(b[i]) - '0' +} + +// Check if the character at the specified position is a hex-digit. +func is_hex(b []byte, i int) bool { + return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' +} + +// Get the value of a hex-digit. +func as_hex(b []byte, i int) int { + bi := b[i] + if bi >= 'A' && bi <= 'F' { + return int(bi) - 'A' + 10 + } + if bi >= 'a' && bi <= 'f' { + return int(bi) - 'a' + 10 + } + return int(bi) - '0' +} + +// Check if the character is ASCII. +func is_ascii(b []byte, i int) bool { + return b[i] <= 0x7F +} + +// Check if the character at the start of the buffer can be printed unescaped. +func is_printable(b []byte, i int) bool { + return ((b[i] == 0x0A) || // . == #x0A + (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E + (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF + (b[i] > 0xC2 && b[i] < 0xED) || + (b[i] == 0xED && b[i+1] < 0xA0) || + (b[i] == 0xEE) || + (b[i] == 0xEF && // #xE000 <= . <= #xFFFD + !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF + !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) +} + +// Check if the character at the specified position is NUL. +func is_z(b []byte, i int) bool { + return b[i] == 0x00 +} + +// Check if the beginning of the buffer is a BOM. +func is_bom(b []byte, i int) bool { + return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF +} + +// Check if the character at the specified position is space. +func is_space(b []byte, i int) bool { + return b[i] == ' ' +} + +// Check if the character at the specified position is tab. +func is_tab(b []byte, i int) bool { + return b[i] == '\t' +} + +// Check if the character at the specified position is blank (space or tab). +func is_blank(b []byte, i int) bool { + //return is_space(b, i) || is_tab(b, i) + return b[i] == ' ' || b[i] == '\t' +} + +// Check if the character at the specified position is a line break. +func is_break(b []byte, i int) bool { + return (b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) +} + +func is_crlf(b []byte, i int) bool { + return b[i] == '\r' && b[i+1] == '\n' +} + +// Check if the character is a line break or NUL. +func is_breakz(b []byte, i int) bool { + //return is_break(b, i) || is_z(b, i) + return ( // is_break: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + // is_z: + b[i] == 0) +} + +// Check if the character is a line break, space, or NUL. +func is_spacez(b []byte, i int) bool { + //return is_space(b, i) || is_breakz(b, i) + return ( // is_space: + b[i] == ' ' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Check if the character is a line break, space, tab, or NUL. +func is_blankz(b []byte, i int) bool { + //return is_blank(b, i) || is_breakz(b, i) + return ( // is_blank: + b[i] == ' ' || b[i] == '\t' || + // is_breakz: + b[i] == '\r' || // CR (#xD) + b[i] == '\n' || // LF (#xA) + b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) + b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) + b[i] == 0) +} + +// Determine the width of the character. +func width(b byte) int { + // Don't replace these by a switch without first + // confirming that it is being inlined. + if b&0x80 == 0x00 { + return 1 + } + if b&0xE0 == 0xC0 { + return 2 + } + if b&0xF0 == 0xE0 { + return 3 + } + if b&0xF8 == 0xF0 { + return 4 + } + return 0 + +} diff --git a/vendor/sigs.k8s.io/yaml/yaml.go b/vendor/sigs.k8s.io/yaml/yaml.go index efbc535d41..fc10246bdb 100644 --- a/vendor/sigs.k8s.io/yaml/yaml.go +++ b/vendor/sigs.k8s.io/yaml/yaml.go @@ -1,3 +1,19 @@ +/* +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 yaml import ( @@ -8,56 +24,59 @@ import ( "reflect" "strconv" - "gopkg.in/yaml.v2" + "sigs.k8s.io/yaml/goyaml.v2" ) -// Marshal marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) +// Marshal marshals obj into JSON using stdlib json.Marshal, and then converts JSON to YAML using JSONToYAML (see that method for more reference) +func Marshal(obj interface{}) ([]byte, error) { + jsonBytes, err := json.Marshal(obj) if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) + return nil, fmt.Errorf("error marshaling into JSON: %w", err) } - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil + return JSONToYAML(jsonBytes) } // JSONOpt is a decoding option for decoding from JSON format. type JSONOpt func(*json.Decoder) *json.Decoder -// Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object, -// optionally configuring the behavior of the JSON unmarshal. -func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error { - return yamlUnmarshal(y, o, false, opts...) +// Unmarshal first converts the given YAML to JSON, and then unmarshals the JSON into obj. Options for the +// standard library json.Decoder can be optionally specified, e.g. to decode untyped numbers into json.Number instead of float64, or to disallow unknown fields (but for that purpose, see also UnmarshalStrict). obj must be a non-nil pointer. +// +// Important notes about the Unmarshal logic: +// +// - Decoding is case-insensitive, unlike the rest of Kubernetes API machinery, as this is using the stdlib json library. This might be confusing to users. +// - This decodes any number (although it is an integer) into a float64 if the type of obj is unknown, e.g. *map[string]interface{}, *interface{}, or *[]interface{}. This means integers above +/- 2^53 will lose precision when round-tripping. Make a JSONOpt that calls d.UseNumber() to avoid this. +// - Duplicate fields, including in-case-sensitive matches, are ignored in an undefined order. Note that the YAML specification forbids duplicate fields, so this logic is more permissive than it needs to. See UnmarshalStrict for an alternative. +// - Unknown fields, i.e. serialized data that do not map to a field in obj, are ignored. Use d.DisallowUnknownFields() or UnmarshalStrict to override. +// - As per the YAML 1.1 specification, which yaml.v2 used underneath implements, literal 'yes' and 'no' strings without quotation marks will be converted to true/false implicitly. +// - YAML non-string keys, e.g. ints, bools and floats, are converted to strings implicitly during the YAML to JSON conversion process. +// - There are no compatibility guarantees for returned error values. +func Unmarshal(yamlBytes []byte, obj interface{}, opts ...JSONOpt) error { + return unmarshal(yamlBytes, obj, yaml.Unmarshal, opts...) } -// UnmarshalStrict strictly converts YAML to JSON then uses JSON to unmarshal -// into an object, optionally configuring the behavior of the JSON unmarshal. -func UnmarshalStrict(y []byte, o interface{}, opts ...JSONOpt) error { - return yamlUnmarshal(y, o, true, append(opts, DisallowUnknownFields)...) +// UnmarshalStrict is similar to Unmarshal (please read its documentation for reference), with the following exceptions: +// +// - Duplicate fields in an object yield an error. This is according to the YAML specification. +// - If obj, or any of its recursive children, is a struct, presence of fields in the serialized data unknown to the struct will yield an error. +func UnmarshalStrict(yamlBytes []byte, obj interface{}, opts ...JSONOpt) error { + return unmarshal(yamlBytes, obj, yaml.UnmarshalStrict, append(opts, DisallowUnknownFields)...) } -// yamlUnmarshal unmarshals the given YAML byte stream into the given interface, +// unmarshal unmarshals the given YAML byte stream into the given interface, // optionally performing the unmarshalling strictly -func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error { - vo := reflect.ValueOf(o) - unmarshalFn := yaml.Unmarshal - if strict { - unmarshalFn = yaml.UnmarshalStrict - } - j, err := yamlToJSON(y, &vo, unmarshalFn) +func unmarshal(yamlBytes []byte, obj interface{}, unmarshalFn func([]byte, interface{}) error, opts ...JSONOpt) error { + jsonTarget := reflect.ValueOf(obj) + + jsonBytes, err := yamlToJSONTarget(yamlBytes, &jsonTarget, unmarshalFn) if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) + return fmt.Errorf("error converting YAML to JSON: %w", err) } - err = jsonUnmarshal(bytes.NewReader(j), o, opts...) + err = jsonUnmarshal(bytes.NewReader(jsonBytes), obj, opts...) if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) + return fmt.Errorf("error unmarshaling JSON: %w", err) } return nil @@ -67,21 +86,26 @@ func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error // object, optionally applying decoder options prior to decoding. We are not // using json.Unmarshal directly as we want the chance to pass in non-default // options. -func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error { - d := json.NewDecoder(r) +func jsonUnmarshal(reader io.Reader, obj interface{}, opts ...JSONOpt) error { + d := json.NewDecoder(reader) for _, opt := range opts { d = opt(d) } - if err := d.Decode(&o); err != nil { + if err := d.Decode(&obj); err != nil { return fmt.Errorf("while decoding JSON: %v", err) } return nil } -// JSONToYAML Converts JSON to YAML. +// JSONToYAML converts JSON to YAML. Notable implementation details: +// +// - Duplicate fields, are case-sensitively ignored in an undefined order. +// - The sequence indentation style is compact, which means that the "- " marker for a YAML sequence will be on the same indentation level as the sequence field name. +// - Unlike Unmarshal, all integers, up to 64 bits, are preserved during this round-trip. func JSONToYAML(j []byte) ([]byte, error) { // Convert the JSON to an object. var jsonObj interface{} + // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the // Go JSON library doesn't try to pick the right number type (int, float, // etc.) when unmarshalling to interface{}, it just picks float64 @@ -93,35 +117,46 @@ func JSONToYAML(j []byte) ([]byte, error) { } // Marshal this object into YAML. - return yaml.Marshal(jsonObj) + yamlBytes, err := yaml.Marshal(jsonObj) + if err != nil { + return nil, err + } + + return yamlBytes, nil } // YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML, // passing JSON through this method should be a no-op. // -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. +// Some things YAML can do that are not supported by JSON: +// - In YAML you can have binary and null keys in your maps. These are invalid +// in JSON, and therefore int, bool and float keys are converted to strings implicitly. +// - Binary data in YAML with the !!binary tag is not supported. If you want to +// use binary data with this library, encode the data as base64 as usual but do +// not use the !!binary tag in your YAML. This will ensure the original base64 +// encoded data makes it all the way through to the JSON. +// - And more... read the YAML specification for more details. +// +// Notable about the implementation: // -// For strict decoding of YAML, use YAMLToJSONStrict. +// - Duplicate fields are case-sensitively ignored in an undefined order. Note that the YAML specification forbids duplicate fields, so this logic is more permissive than it needs to. See YAMLToJSONStrict for an alternative. +// - As per the YAML 1.1 specification, which yaml.v2 used underneath implements, literal 'yes' and 'no' strings without quotation marks will be converted to true/false implicitly. +// - Unlike Unmarshal, all integers, up to 64 bits, are preserved during this round-trip. +// - There are no compatibility guarantees for returned error values. func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil, yaml.Unmarshal) + return yamlToJSONTarget(y, nil, yaml.Unmarshal) } // YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding, // returning an error on any duplicate field names. func YAMLToJSONStrict(y []byte) ([]byte, error) { - return yamlToJSON(y, nil, yaml.UnmarshalStrict) + return yamlToJSONTarget(y, nil, yaml.UnmarshalStrict) } -func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, interface{}) error) ([]byte, error) { +func yamlToJSONTarget(yamlBytes []byte, jsonTarget *reflect.Value, unmarshalFn func([]byte, interface{}) error) ([]byte, error) { // Convert the YAML to an object. var yamlObj interface{} - err := yamlUnmarshal(y, &yamlObj) + err := unmarshalFn(yamlBytes, &yamlObj) if err != nil { return nil, err } @@ -136,7 +171,11 @@ func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, } // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) + jsonBytes, err := json.Marshal(jsonObj) + if err != nil { + return nil, err + } + return jsonBytes, nil } func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { @@ -147,13 +186,13 @@ func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (in // decoding into the value, we're just checking if the ultimate target is a // string. if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) + jsonUnmarshaler, textUnmarshaler, pointerValue := indirect(*jsonTarget, false) // We have a JSON or Text Umarshaler at this level, so we can't be trying // to decode into a string. - if ju != nil || tu != nil { + if jsonUnmarshaler != nil || textUnmarshaler != nil { jsonTarget = nil } else { - jsonTarget = &pv + jsonTarget = &pointerValue } } @@ -205,7 +244,7 @@ func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (in keyString = "false" } default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", + return nil, fmt.Errorf("unsupported map key of type: %s, key: %+#v, value: %+#v", reflect.TypeOf(k), k, v) } diff --git a/vendor/sigs.k8s.io/yaml/yaml_go110.go b/vendor/sigs.k8s.io/yaml/yaml_go110.go index ab3e06a222..94abc1719d 100644 --- a/vendor/sigs.k8s.io/yaml/yaml_go110.go +++ b/vendor/sigs.k8s.io/yaml/yaml_go110.go @@ -1,7 +1,24 @@ // This file contains changes that are only compatible with go 1.10 and onwards. +//go:build go1.10 // +build go1.10 +/* +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 yaml import "encoding/json"